Reflection-Based Object Comparison in Tests

I often use Apache Commons for maintainable reflection-based equals and hashCode methods. Quite frequently I used to add this equals implementation for comparisons in tests only. Then I used to add hashCode as well for consistency. This might be considered a test logic in production code but I was not particularly worried about this. The reason it did not bother me was that the implementation of these methods makes a lot of sense on its own.

Recently, I came across a library that does a slightly better job. Unitils provides assertions that use reflection. Instead of adding equals method in the class and comparing the objects using regular assertion you can write the following in the test:

assertReflectionEquals(object1, object2);

This will perform a deep comparison in a similar way to reflection equals from Apache Commons. This way equals and hashCode methods can be avoided in production code if not needed. The production code may also have a completely different equals implementation without affecting the tests.

Share
This entry was posted in Java and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>