我 User
已将 User
对象转换为Kotlin,当我在Java中运行现有的JUnit测试时,我在Kotlin User
对象的两个实例之间出现错误 .
User.kt:
data class User (
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
var id: Long? = null,
...
)
TestUtil.java
import static org.assertj.core.api.Assertions.assertThat;
public class TestUtil {
public static void equalsVerifier(Class clazz) throws Exception {
Object domainObject1 = clazz.getConstructor().newInstance();
// Test with an instance of the same class
Object domainObject2 = clazz.getConstructor().newInstance();
assertThat(domainObject1).isNotEqualTo(domainObject2);
}
}
assertThat(domainObject1).isNotEqualTo(domainObject2)
测试失败,因为我相信Java比较在Kotlin类上没有正确完成 . 如果我通过调试器运行它,我可以看到 domainObject1
和 domainObject2
是不同的实例 .
是否可以通过这个测试用例?相同的测试用例用于其他Java类,因此它必须适用于Java和Kotlin类 .
2 回答
在Kotlin中,
data class
会自动生成equals()
以检查属性是否相等 .引自“Kotlin in Action”:
如果要在不修改测试用例的情况下传递测试用例,可以覆盖数据类的
equals()
以检查referential equality .请注意,如果有任何函数依赖于您的数据类的structural equality,它可能会影响您的其他代码 . 所以,我建议您参考@ shawn的答案来改变您的测试用例 .
isNotEqualTo
调用equals
. Kotlin类为data class
实现了正确的equals
方法 . 所以domainObject1.equals(domainObject2)
是真的 . 这种行为是正确的 .只需看看AssertJ文档:
我想你应该试试: