java java中junit测试中的断言错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37251557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:20:12  来源:igfitidea点击:

assertion error in junit test in java

javajunit

提问by mer mer

guys i have this service

伙计们,我有这项服务

public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentDao departmentDao;
    //... other functions 

    @Override
    public Department getDepartment(int depid) {
        return departmentDao.getDepartment(depid);
    }
}

and my test unit is

我的测试单元是

Department department = new Department();

@Autowired
private DepartmentDao myDao;

@Autowired
private DepartmentService service;


@Test
public void testGetDepartment(){
    department.setDepId(111);
    department.setDepName("merna");
    assertEquals(department, service.getDepartment(111));
}

but it gives me

但它给了我

java.lang.AssertionError: expected:<com.dineshonjava.model.Department@f9b5552> but was:<com.dineshonjava.model.Department@4d4960c8>

any help ??

任何帮助?

回答by Daniel Almeida

You should override the equals method in your Department class:

您应该覆盖 Department 类中的 equals 方法:

public boolean equals(Object object) {
      if(object == null) {
          return false;
      } 
      if(this == object) {
          return true;
      }
      Department otherDepartment = (Department) object;
      if(this.getDepId() == otherDepartment.getDepId()) {
          return true;
      } else {
          return false;
      }
}

回答by Rahul Kumar

you are trying to assert two different java object which are logically same, One which you created and other is returned by the service.

您试图断言两个逻辑上相同的不同 java 对象,一个是您创建的,另一个是由服务返回的。

As told in comments by someone that you need to override your equal method and provide the logic as on what basis those two object are equal. in you case I guess two different Department object are equal if they have same depId. This logic should be there in equals method of Department.java for assertEqual to work.

正如有人在评论中所说的那样,您需要覆盖您的 equal 方法并提供逻辑作为这两个对象相等的基础。在你的情况下,我猜如果两个不同的部门对象具有相同的 depId,它们是相等的。这个逻辑应该存在于 Department.java 的 equals 方法中,以便 assertEqual 工作。

Alternatively if you don't want to do that, you can check for particular primitive value rather than the whole object comparison.

或者,如果您不想这样做,您可以检查特定的原始值而不是整个对象比较。

@Test
public void testGetDepartment(){
 department.setDepId(111);
 department.setDepName("merna");
 assertEquals(department.getDepName(), service.getDepartment(111).getDepName());
}

But this is assuming that value you are putting in test case is same as it's being returned by DB (or from wherever).

但这是假设您放入测试用例的值与 DB(或从任何地方)返回的值相同。