Using commons EqualsBuilder in JUnit tests
A common JUnit test w/ databases is to create an object (or hierarchy of objects), save them, and then retrieve them back. You want to see if what you put in is what you get out.
These tests can be cumbersome to write, becuase comparing the inserted object with the fetched object will require the following test for each attribute of the class.
So if there are 20 attributes, you have 20 assertEquals() to perform. And if you should happen to have a collection of child objects too, well, you've really got your work cut out for you.
So one way around this is to use the commons EqualsBuilder class and it's reflectionEquals() method.
This will do a full comparison of the objects on all of their attributes, instead of using their equals methods. And if you have a collection in your class, it will take the collections and compare them. At the collection level, however, it reverts back to the equals() method on the children of the respective collections (95% sure about that).
These tests can be cumbersome to write, becuase comparing the inserted object with the fetched object will require the following test for each attribute of the class.
assertEquals( insertedObj.getAttribute1(),
fetchedObj.getAttribute1() );
So if there are 20 attributes, you have 20 assertEquals() to perform. And if you should happen to have a collection of child objects too, well, you've really got your work cut out for you.
So one way around this is to use the commons EqualsBuilder class and it's reflectionEquals() method.
import org.apache.commons.lang.builder.EqualsBuilder;
....
public void testStuff()
{
assertTrue("Compare inserted obj w/ fetched obj",
EqualsBuilder.reflectionEquals(insertedObj, fetchedObj));
}
This will do a full comparison of the objects on all of their attributes, instead of using their equals methods. And if you have a collection in your class, it will take the collections and compare them. At the collection level, however, it reverts back to the equals() method on the children of the respective collections (95% sure about that).

