Hamcrest compare collections
To assert collections have the same elements but don't care about their order, use Hamcrest's containsInAnyOrder
:
For the times when you do care about order, switch to contains
:
Both examples show how to use Hamcrest matchers for comparing collections.
Comparing list equality
If you need to check if two lists are identical, here is how you do it:
Type check: the silent hero of code
Make sure your list's type is the one that the matcher expects:
Picking out items in a haystack
Looking for the proverbial one
Using hasItem
, you can check for a single item:
All for one, or just more than one
To check for multiple items, use hasItems
:
The super-matchmaker
Combine multiple matchers by using allOf
:
Property matchers, the unsung heroes
hasProperty
can be employed for comparing object attributes within collections:
Remember to import org.hamcrest.Matchers.is
.
Pay attention to details
Converting lists to arrays for fun and profit
When it's easier to compare by converting a list to an array:
Avoiding the common "whoops"!
When using matchers, watch out for type safety and correct usage to avoid funny but hard-to-find bugs.
Readable assertions: we got you covered.
To make your assertions more readable, import containsInAnyOrder
statically.
Was this article helpful?