首页 文章

Kotlin类实例断言不正确

提问于
浏览
1

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类上没有正确完成 . 如果我通过调试器运行它,我可以看到 domainObject1domainObject2 是不同的实例 .

是否可以通过这个测试用例?相同的测试用例用于其他Java类,因此它必须适用于Java和Kotlin类 .

2 回答

  • 1

    在Kotlin中, data class 会自动生成 equals() 以检查属性是否相等 .

    引自“Kotlin in Action”:

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

    如果要在不修改测试用例的情况下传递测试用例,可以覆盖数据类的 equals() 以检查referential equality .

    override fun equals(other: Any?) = this === other
    

    请注意,如果有任何函数依赖于您的数据类的structural equality,它可能会影响您的其他代码 . 所以,我建议您参考@ shawn的答案来改变您的测试用例 .

  • 1

    isNotEqualTo 调用 equals . Kotlin类为 data class 实现了正确的 equals 方法 . 所以 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);
    

相关问题