How does Hamcrest hasItems contain and contain InAnyOrder different?

Hamcrest provides a number of matches for approving the contents of a collection. All these cases pass:

Collection<String> c = ImmutableList.of("one", "two", "three"); assertThat(c, hasItems("one", "two", "three"); assertThat(c, contains("one", "two", "three"); assertThat(c, containsInAnyOrder("one", "two", "three"); 

How are hasItems , contains and containsInAnyOrder different?

+18
hamcrest
Nov 21 '15 at 6:41
source share
1 answer

hasItems checks :

consecutive passes over the considered Iterable give at least one element that is equal to the corresponding element from the specified items .

That is, it ensures that collections contain at least these elements in any order. In this way,

 assertThat(c, hasItems("one", "two")); 

will also pass, with the additional element being ignored. BUT:

 assertThat(c, hasItems("three", "two", "one")); 

will also be held.

contains checks :

one pass through the tested Iterable gives a number of elements, each of which is logically equal to the corresponding element in the specified elements. For a positive match, the checked iteration should be the same length as the number of specified elements.

Therefore, he guarantees that the collection contains precisely these elements:

 assertThat(c, contains("one", "two")); // Fails 

This will not succeed, since the remaining "three" will not match.

 assertThat(c, contains("three", "two", "one")); // Fails 

This fails because the matching elements do not match.

Another associated helper, containsInAnyOrder , checks that these elements are present, but in any order:

Creates an agnostic order attribute for Iterables , which matches when one pass through the tested Iterable gives a series of elements, each of which is logically equal to one element anywhere in the specified elements.

A test with a missing item fails:

 assertThat(c, containsInAnyOrder("one", "two")); // Fails 

But all items in a different order will pass:

 assertThat(c, containsInAnyOrder("three", "two", "one")); 
+22
Nov 21 '15 at 6:41
source share



All Articles