Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do unit test for 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; } 
like image 715
Tomasz Gutkowski Avatar asked Dec 15 '10 12:12

Tomasz Gutkowski


People also ask

Why equals () and hashCode () method used?

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.

What does the hashCode () method?

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.


1 Answers

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()); } 
like image 66
duffymo Avatar answered Sep 20 '22 16:09

duffymo