You can combine is
and equalTo
of matchers library. The assert statement looks longer but the error message is better. Since contains
is fail first it breaks when it finds the first mismatch and wouldn't find failures further down the list. Where as is
and equalTo
will print the entire list from which you see all the mismatches.
Example using contains
List<String> list = Arrays.asList("foo", "bar", "boo");
assertThat(list, contains("foo", "boo", "bar"));
Gives the following error message:
Expected: iterable containing ["foo", "boo", "bar"]
but: item 1: was "bar"
Example using is and equalTo
List<String> list = Arrays.asList("foo", "bar", "boo");
assertThat(list, is(equalTo(Lists.newArrayList("foo", "boo", "bar"))));
Gives the following error message:
Expected: is <[foo, boo, bar]>
but: was <[foo, bar, boo]>
The second method doesn't tell you the index where the mismatch is but to me this is still better as you can fix the test by looking at the failure message just once. Whereas in method one, you'll first fix index 1, run the test, detect mismatch at index 2 and do the final fix.
Matchers.contains
method checks that the list contains exactly the expected items. – Broadbrim