Equals and HashCode Part III: Unit Testing

Over the last two posts we have been looking at the equals and hashcode methods by way of implementing our own HashMap.

If you are feeling daring and want to start actually overriding these methods, you will of course want to test them. In the interest of test-first, let’s look at testing techniques before we get to the nuts and bolts of implementing equals and hashcode! Let’s review some of the options for unit testing equals and hashCode:

Roll Your Own

Many people start by reviewing the contracts as defined the the API and writing individual unit tests for each part of the contract for equals and hashcode. After a point, they realize that the testing of their code can be refactored into reusable code. The sample listed here looks useful albeit not actively developed.

JUnit Extensions

If you like sticking with what your framework gives you, you will probably look at JUnit Extensions and find EqualsHashCodeTestCase. This option is closer to being an actual part of JUnit, but the code here is older and requires your test classes extend a particular TestCase, not to mention requiring you to write code for specific objects to test against.

JUnit Theories

There is a way to use JUnit Theories to test equals and hashCode. This technique is newer than EqualsHashCodeTestCase but a little harder to use, as again you need to define all the objects as @DataPoints for use in testing. Additionally it requires the test to be run with its own test runner which would require you to break your test apart if you want to test these methods in a test class already using another test runner.

EqualsVerifier

After a bit of research I found a test technique that I think is the most modern, comprehensive, and easy to use: EqualsVerifier. Once you include the library as a test dependency, unit testing your equals and hashcode methods can be as simple as

@Test
public void testEqualsHashCode() {
    EqualsVerifier.forClass(My.class).verify();
}

The library is actively maintained and you can feel free to jump in to the google group or check out the code on github. The owner is friendly and responsive, so issue reports and pull requests are welcome!

Advertisements

1 Comment

Filed under Software Engineering

One response to “Equals and HashCode Part III: Unit Testing

  1. Thanks for the EqualsVerifier pointer. There’s also meanBean (http://meanbean.sourceforge.net) although it’s not been updated for a while and looks like EqualsVerifier is regularly updated.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s