我不明白为什么这会给我一个错误,两个对象都是平等的,可能会发生什么? 我认为,Pet集合有问题,因为如果删除它,一切正常。
java.lang.AssertionError: expected: org.company.petshop.domains.Person<Person [id=10, dni=3547249, email=jdoe@mail.com, firstName=John, lastName=Doe, username=johndoe, password=johndoe, role=USER_ROLE, status=Active, pets=[]]>
but was: org.company.petshop.domains.Person<Person [id=10, dni=3547249, email=jdoe@mail.com, firstName=John, lastName=Doe, username=johndoe, password=johndoe, role=USER_ROLE, status=Active, pets=[]]>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at org.company.petshop.services.PersonServicesTests.testPersonShouldBeSaved(PersonServicesTests.java:24)
单元测试是:
public class PersonServicesTests {
@Autowired
private IGenericService<Person> personService;
@Test
public void testPersonShouldBeSaved() {
Person p = new Person(3547249, "jdoe@mail.com", "John", "Doe", "johndoe", "johndoe", "USER_ROLE");
personService.create(p);
assertEquals(p, personService.findById(10));
}
}
等于方法:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (dni == null) {
if (other.dni != null)
return false;
} else if (!dni.equals(other.dni))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (role == null) {
if (other.role != null)
return false;
} else if (!role.equals(other.role))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (tasks == null) {
if (other.tasks != null)
return false;
} else if (!tasks.equals(other.tasks))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
答案 0 :(得分:1)
使用内置的equals
进行此类测试不是一个好主意,原因如下:
equals
,如果以后更改(通常是出于商业原因),那么您的测试可能现在已经过去,但它不应该equals
方法保持最新。我建议使用我们编写的sameBeanAs
方法,该方法将进行反射性深层对象比较,同时为您提供良好的诊断。您可以像这样使用它:
assertThat(p, sameBeanAs(personService.findById(10)));
有关如何使用和访问
的信息,请参阅here