Should I unit test hashCode/equals/toString?

If you generate those methods, you should probably also generate the tests for it ;-)

It may be cumbersome to test those methods by hand but depending on what you want to ensure with your tests, it might be worth to test those methods as well. Counter-question: would you test log-statements?

It really depends on what you are trying to accomplish. Some will say: don't, others may say: do.

Thinking about some reasons to not test such methods:

  • code is generated and may contain lots of fields. testing it may lead to lots of various combinations which would just be cumbersome to write/maintain and maybe the generator was already tested good enough? ;-)
  • you do not gain any value by implementing tests for it. Your toString() will only be used by logs or by the debugger, so you don't even care.
  • you trust that the generated code is safe enough for hashcode and equals

Reasons to test such methods:

  • to ensure that the outcome is as expected
  • you want to ensure that if you regenerate those methods, it doesn't break previous method implementation usages
  • you use your toString()-method besides logging and don't want certain things to show up there. As Hulk stated, you may also want to ensure that certain things don't even show up in logs.

But these were rather made up. In the last projects I did not test toString() and equals or hashCode only seldomly as it wasn't considered necessary and everyone agreed.

It may all come down to: how safe you want your code to be and how much worth is it to you (or your business or your customer ;-))


The problem with IDE generated hashCode/equals is that it can get out of sync with the object itself (for example when you add new fields). I would therefore advise to create tests for hashCode and equals.

It would be of course sub-optimal to write these by hand. You can use automated tools such as the EqualsVerifier project to make these a one-liner.

toString is a different beast as it doesn't have any contract defined. If you use toString just to get a nicer debugging experience, I wouldn't test it and would just remove it from coverage calculations.


Yes, I would test all of these. Its not good enough to say, no tests needs as they are auto generated. Some one can easily add a new field and forget to regenerate the equals/ hash code and to string.

Testing to string is perhaps the most controversial of the lot, but I think its needed especially if you are logging in your application.

As already suggested by other, EqualsVerifier is probably the best approach for testing equals and hash code.

As for testing the toString method, try ToStringVerifier. The test is as simple as:

@Test
public void testToString() {
    ToStringVerifier.forClass(User.class)
                  .withClassName(NameStyle.SIMPLE_NAME)
                  .verify();
}