How to write Object Equality assertions correctly with JUnit

Andrew Larsen
3 min readNov 19, 2023

When writing JUnit tests, often times we run into a situation where we need to check if an object we receive is equal to the object that we expect.

In order to test equality, the assertEquals method invokes the object’s .equals() method. By default, the .equals() method compares two object’s addresses in memory, which means the above example test will fail.

One way to solve for this is to override the HelloObject’s .equals() and .hashCode() methods

This allows us to simply assert on the .equals method