Kotlin类实例断言不正确

Kotlin类实例断言不正确,kotlin,Kotlin,我正在将一个Java项目转换为Kotlin。我已经将一个User对象转换为Kotlin,当我在Java中运行现有的JUnit测试时,我在KotlinUser对象的两个实例之间得到一个错误 User.kt: data class User ( @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGener

我正在将一个Java项目转换为Kotlin。我已经将一个
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)
测试失败,因为我相信在Kotlin类上没有正确地进行Java比较。如果我通过调试器运行它,我可以看到
domainObject1
domainObject2
是不同的实例


有可能让这个测试用例通过吗?相同的测试用例用于其他Java类,因此它必须同时适用于Java和Kotlin类。

isNotEqualTo调用
equals
。Kotlin类为
数据类
实现了正确的
等于
方法。所以
domainObject1.equals(domainObject2)
是真的。这种行为是正确的

请看AssertJ文档:

isNotSameAs(Object other): 
   Verifies that the actual value is not the same as the given one, 
   ie using == comparison.
我想你应该试试:

    assertThat(domainObject1).isNotSameAs(domainObject2);
在Kotlin中,
equals()
自动为
数据类生成,以检查属性是否相等

引用“Kotlin在行动”:

生成的equals()方法检查所有属性的值是否相等。。。请注意,未在主构造函数中声明的属性不参与等式检查和哈希代码计算

如果希望在不修改测试用例的情况下通过测试用例,可以覆盖要检查的数据类的
equals()


请注意,如果有依赖于数据类的函数,它可能会影响其他代码。因此,我建议您参考@shawn的答案来更改您的测试用例。

如果您删除
数据
关键字,失败的测试将通过,这是因为Kotlin将生成
equals
方法来与主构造函数中的属性进行比较。
override fun equals(other: Any?) = this === other