Best way to unit test Collection?
- by limc
I'm just wondering how folks unit test and assert that the "expected" collection is the same/similar as the "actual" collection (order is not important).
To perform this assertion, I wrote my simple assert API:-
public void assertCollection(Collection<?> expectedCollection, Collection<?> actualCollection) {
assertNotNull(expectedCollection);
assertNotNull(actualCollection);
assertEquals(expectedCollection.size(), actualCollection.size());
assertTrue(expectedCollection.containsAll(actualCollection));
assertTrue(actualCollection.containsAll(expectedCollection));
}
Well, it works. It's pretty simple if I'm asserting just bunch of Integers or Strings. It can also be pretty painful if I'm trying to assert a collection of Hibernate domains, say for example. The collection.containsAll(..) relies on the equals(..) to perform the check, but I always override the equals(..) in my Hibernate domains to check only the business keys (which is the best practice stated in the Hibernate website) and not all the fields of that domain. Sure, it makes sense to check just against the business keys, but there are times I really want to make sure all the fields are correct, not just the business keys (for example, new data entry record). So, in this case, I can't mess around with the domain.equals(..) and it almost seems like I need to implement some comparators for just unit testing purposes instead of relying on collection.containsAll(..).
Are there some testing libraries I could leverage here? How do you test your collection?
Thanks.