如何对hashCode()进行单元测试? [英] How can I do unit test for hashCode()?
本文介绍了如何对hashCode()进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在单元测试中测试hashCode()函数?
How can I test the hashCode() function in unit testing?
public int hashCode(){
int result = 17 + hashDouble(re);
result = 31 * result + hashDouble(im);
return result;
}
推荐答案
每当我覆盖equals和hash代码时,我都会按照Joshua Bloch在有效Java"第3章中的建议编写单元测试.是自反的,对称的和可传递的.我还确保不等于"对所有数据成员均正常工作.
Whenever I override equals and hash code, I write unit tests that follow Joshua Bloch's recommendations in "Effective Java" Chapter 3. I make sure that equals and hash code are reflexive, symmetric, and transitive. I also make sure that "not equals" works properly for all the data members.
当我检查对equals的调用时,我还要确保hashCode的行为符合预期.像这样:
When I check the call to equals, I also make sure that the hashCode behaves as it should. Like this:
@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());
}
这篇关于如何对hashCode()进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文