Comparing Collections in Junit
There come a time for every developer that you write a test and need to perform some assertion on a Collection.
In this assertion you need to verify if some members (or all of them) exit or not.
The naive and simple way is to assert the same logical condition on each collection member.
For example assert if it exists in the collection or not.
This technique has several downfalls:
- If the collection is very big, you will have to perform the same assertion over and over…
- if the assertion fail, the output of the assertion is <false> without any informative text.
To overcome this problem I will use Hamcrest.
In my code I have replaced all of the members of some collection with others.
Now, when I come to test it I can do it in a single line of code:
assertThat(Collections.disjoint(classUnderTest.getMembers(), copyOfExistingMembers), Matchers.is(true));
I will use:
assertThat(classUnderTest.getMembers(), not(containsInAnyOrder(copyOfExistingMembers.toArray(new Record[copyOfExistingMembers.size()]))))
classUnderTest.getMembers() return a List<>.
- containsInAnyOrder is an Hamcrest Matcher that verify a given Collection contain all values in some order.
I’m passing it an Array with items that shouldn’t be in the List<>
- not is an other Hamcrest Matcher that test a given condition isn’t true.