如何对 hashCode() 进行单元测试?

2022-08-31 23:51:15

如何在单元测试中测试hashCode()函数?

public int hashCode(){
    int result = 17 + hashDouble(re);
    result = 31 * result + hashDouble(im);
    return result;
}

答案 1

每当我覆盖等式和哈希代码时,我都会编写单元测试,这些测试遵循Joshua Bloch在“Effective Java”第3章中的建议。我确保等式和哈希代码是自反的、对称的和可传递的。我还确保“不等于”对所有数据成员都正常工作。

当我检查对 equals 的调用时,我还确保哈希代码的行为符合预期。喜欢这个:

@Test
public void testEquals_Symmetric() {
    Person x = new Person("Foo Bar");  // equals and hashCode check name field value
    Person y = new Person("Foo Bar");
    Assert.assertTrue(x.equals(y) && y.equals(x));
    Assert.assertTrue(x.hashCode() == y.hashCode());
}

答案 2

当您编写一般的数学函数(如哈希代码)时,您将在测试中测试一些示例,直到您确信该函数按预期工作。示例数取决于您的函数。

对于哈希代码函数,我认为您至少测试了两个不同的对象,它们被认为是相等的,具有相同的哈希代码。喜欢

assertNotSame(obj1, obj2); // don't cheat
assertEquals(obj1.hashcode(), obj2.hashcode());

此外,您应该测试两个不同的值是否具有不同的哈希代码,以避免实现类似 .hashcode()return 1;