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

Tom*_*ski 35 java junit unit-testing hashcode

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

public int hashCode(){
    int result = 17 + hashDouble(re);
    result = 31 * result + hashDouble(im);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

duf*_*ymo 75

每当我覆盖equals和hash代码时,我都会按照Joshua Bloch在"Effective Java"第3章中的建议编写单元测试.我确保equals和hash代码是自反的,对称的和传递的.我还确保"not equals"适用于所有数据成员.

当我检查对equals的调用时,我也确保hashCode的行为应该如此.像这样:

@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());
}
Run Code Online (Sandbox Code Playgroud)

  • 最重要的是,您可以补充说,测试对非关键字段的修改不会导致生成修改后的hashCode是合理的.对关键字段的修改也会导致修改的hashCodes. (13认同)

Der*_*ike 5

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

对于哈希码函数,我认为你至少测试了两个不同的对象,它们被认为是相同的哈希码.喜欢

assertNotSame(obj1, obj2); // don't cheat
assertEquals(obj1.hashcode(), obj2.hashcode());
Run Code Online (Sandbox Code Playgroud)

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