如何测试 unit testing 中的 hashCode() 函数?
public int hashCode(){
int result = 17 + hashDouble(re);
result = 31 * result + hashDouble(im);
return result;
}
最佳答案
每当我重写 equals 和 hash 代码时,我都会按照 Joshua Bloch 在“Effective Java”第 3 章中的建议编写单元测试。我确保 equals 和 hash 代码是自反的、对称的和传递的。我还确保“不等于”适用于所有数据成员。
当我检查对 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());
}
关于java - 如何对 hashCode() 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4449728/