Skip to Content
Author's profile photo Former Member

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:

  1. If the collection is very big, you will have to perform the same assertion over and over…
  2. if the assertion fail, the output of the assertion is <false> without any informative text.


To overcome this problem I will use Hamcrest.

If you are not familiar with Hamcrest you should read my previous blog: Hamcrest, Junit bests friend

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:

Instead of:

assertThat(Collections.disjoint(classUnderTest.getMembers(), copyOfExistingMembers),;

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.

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.