Thursday, July 26, 2012

Utility to Compare Similar Objects

Every once in a while I find I have to make similar objects that need to map to each other (basicaly copy like fields from one object to the other) and I wanted a simpler way to make sure that my mappings were correct for my unit tests.

Of course there is the manual way of doing assertEquals(object1.getValue1(), object2.getValue1()) but it does get tedious after the first two or three. Of course with this way you may be more likely not to overlook any fields since you effectively have to do it once during your mapping and then again during your unit test.

Another way to do it is to use reflection. I created a utility that will grab all the getters from one object and try to compare it to the getters of the same name of another object. For example: in Object1 we have getValue1() and in Object2 we have getValue1(). The utility would run through Object1 and grab the getter getValue1() and then try to compare the return results to a getValue1() on Object2. If the values don't match or if Object2 doesn't have that getter than the name of the getter is added to a list.

A better way to explain it is with the code. Below is the utility as well as a test that shows how it can be used.

No comments:

Post a Comment