【发布时间】:2015-02-20 20:42:28
【问题描述】:
我不明白为什么这会给我一个错误,两个对象都是相等的,会发生什么? 我认为,宠物收藏有问题,因为如果我删除它,一切正常。
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));
}
}
equals 方法:
@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;
}
【问题讨论】:
-
我打赌你委托给的
equals方法没有实现(正确的方式)。 -
我应该在没有宠物集合的情况下实施 equals 吗?因为在那种情况下一切正常!
-
堆栈转储中唯一未显示的字段是任务。如果它包含在 toString() 中会显示什么?
-
你使用的是数组还是集合的equals方法?那么这就是你委派的不正确的equals方法。他们只检查对象身份而不是相同的内容。
-
我看到的两件事可能是错误的,首先是班级检查。 Hibernate 可以为你的人生成一个代理,这可能导致一个人不是一个人而是一个 Person$EnhancedByCglib$2 或类似的东西。接下来,您正在执行一个
tasks.equals(other.tasks)将失败的集合,您将必须比较该集合的内容并确保集合中的元素也具有正确的 equals 方法。
标签: java spring hibernate junit