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; }
Both methods, equals() and hashcode() , are used in Hashtable , for example, to store values as key-value pairs. If we override one and not the other, there is a possibility that the Hashtable may not work as we want, if we use such object as a key.
The Java hashCode() Method hashCode in Java is a function that returns the hashcode value of an object on calling. It returns an integer or a 4 bytes value which is generated by the hashing algorithm.
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.
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With