Analysis of different strategies for comparing two objects - TestMonkeys/jEntityTest GitHub Wiki
Analysis of different strategies for comparing two objects
Currently we can identify 2 existing strategies commonly available for object comparison in a test, and jEntityTest as a 3rd option. Below is an analysis of the strategies.
Comparing each field
Comparing each field is a quick and dirty solution to compare two objects, where the code would look like this:
assertEquals(expectedUser.getFirstName(),actualUser.getFirstName());
assertEquals(expectedUser.getLastName(),actualUser.getLastName());
The more fields an object has - the longer this assert block will be.
pros: quick solution
cons: the test will fail on the first assertion, wich may lead to other bugs not being found right away. When the model gets extended, let's suppose another field like Address is added - there will be a lot of places that need to be updated, or someone might even forget to update the tests.
Overriding equals method
Overriding the equals method solves a lot of the issues described in the previous strategy by centralizing the comparison mechanism and is overall recommended. An example would be:
@Override
public boolean equals(Object o) {
if (!(o instanceof User)) {
return false;
}
User user = (user) o;
if (this.firstName!=user.getFirstName)
return false;
if (this.lastName!=user.getLastName)
return false;
}
In this case we can use a simel assertEquals on the two instances, and we'll get a correct comparison. But although this example is cleaner it still has a few issues.
pros: logic is defined at the object level, comparison can be tweaked
cons: there is no guarantee the equal method will be updated when adding new fields; on a failure - we won't get the detailed info about which field was not as expected.
JEntityTest
JEntityTest solves the issues from the previous strategies by providing a configurable mechanism of comparison, that first inspects the objects, and compares them at field level, afterwards generating a full report on the mismatched fields. Furthermore in the event of the model being enhanced - it will automatically pick the new fields for comparison.
simple usage example: 'assertThat(actualUser, Entity.isEqualTo(expectedUser));'
For a mismatch - we'll get the following output:
java.lang.AssertionError:
Property: User.lastName
Expected: Flimsy
Actual: Does
Comparison was performed using SimpleTypeComparator