如何在单元测试中测试hashCode()函数?
public int hashCode(){
int result = 17 + hashDouble(re);
result = 31 * result + hashDouble(im);
return result;
}
如何在单元测试中测试hashCode()函数?
public int hashCode(){
int result = 17 + hashDouble(re);
result = 31 * result + hashDouble(im);
return result;
}
@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());
}
assertNotSame(obj1, obj2); // don't cheat
assertEquals(obj1.hashcode(), obj2.hashcode());
hashcode()
像return 1;
这样的代码。为了使HashSet/HashMap等实例中具有相同字段的对象被视为相同,重写了hashCode方法。因此,Junit测试应该断言两个具有相同值的不同实例返回相同的hashCode。
创建(数百万)可再现的随机对象,并将所有hashCode添加到Set中,检查您获得几乎与生成的id数量相同的独特值。为了使它们成为可再现的随机数,请使用固定的随机种子。
此外,检查您是否可以将这些项目添加到HashSet中并再次找到它们。(使用相同值的不同对象)
确保您的equals()与您的hashCode()行为匹配。我还会检查您的字段是否都是最终的。
我认为没有必要对哈希码方法进行单元测试,特别是如果它是由你的IDE或HashCodeBuilder
(apache commons)生成的。
@Test
public void testHashcode() {
Person p1 = new Person("Foo Bar");
Person p2 = new Person("Foo Bar");
Map<Person, String> map = new HashMap<>();
map.put(p1, "dummy");
Assert.assertEquals("dummy", map.get(p2));
}