How to test objects equality if they don't implement Object#equals()

Problem: There are cases when you want to test whether two objects are equal, mean did they contain same state or not ? This occurs mostly when you're trying to test JAXB generated beans or any VO/DTO which doesn’t' implement Object#equals() method or/and whose source code you can't modify .

Solution: I knew there is a class (Commons lib's EqualsBuilder class) available which "reflectively" creates the equals method for you taking care all the rules for writing good equals method. But that class doesn’t have a method to test whether two object are equal or not.
At back of my mind, I know Mockito library internally uses the same commons class to solve my problem. I quickly scan the mockito jar and found this class. Here is the code snippet for the same (please note, you have to add mockito jar on classpath for this)
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
public <T> void assertObjectEquals(final T expected, final T actual) {
     assertTrue(new ReflectionEquals(actual, 
This why Mockito is so famous, it makes your testing easy especially with mocks.


This is easy solution but
1) This is an internal class which should not be used by clients. You will put your project into a risk using this.
2) The failed test says nothing about differences:
java.lang.AssertionError: expected [true] but found [false]
Expected :true
Actual :false

Popular Posts