Java – Test two instances of object are equal JUnit


I have two objects A and B. Object A is actual result I get during JUnit test. Object B is I do a actual end db call and assume as expected review. I need to assert that two object instances A and B are equal in value and not actual object.

We have a method called assertEquals(obj expected, obj actual) in JUnit but I don't want that way.

Is there a way or workaround to achieve the same?

Best Answer

Think about exactly what it is you're trying to achieve. Do you want to test object identity or verify that the two objects have exactly the same data? From your suggestion of assertEquals I am guessing you want to go field-by-field.

If the objects are shallow you can use

assertThat(actual, samePropertyValuesAs(expected));

This fails when the object is a composite though. If you want to walk the entire graph you can use the sameBeanAs matcher we wrote some time back to address this issue:

assertThat(actual, sameBeanAs(expected));

If you're using AssertJ then you can also use the built-in functionality like this:


Updated in 06/21 - apparently this is deprecated and has been replaced with:


One thing you don't want to do it override the equals method for this as that might change in the future to accommodate business need.