How to check using Hamcrest if given collection is containing given items in given order? I tried hasItems
but it simply ignores the order.
List<String> list = Arrays.asList("foo", "bar", "boo"); assertThat(list, hasItems("foo", "boo")); //I want this to fail, because the order is different than in "list" assertThat(list, hasItems("boo", "foo"));
Class StringContains. Tests if the argument is a string that contains a substring. Creates a matcher that matches if the examined String contains the specified String anywhere.
Hamcrest is typically viewed as a third generation matcher framework. The first generation used assert(logical statement) but such tests were not easily readable. The second generation introduced special methods for assertions, e.g., assertEquals() .
Matchers is an external addition to the JUnit framework. Matchers were added by the framework called Hamcrest. JUnit 4.8. 2 ships with Hamcrest internally, so you don't have to download it, and add it yourself. Matchers are used with the org.
You can use contains
matcher instead, but you probably need to use latest version of Hamcrest. That method checks the order.
assertThat(list, contains("foo", "boo"));
You can also try using containsInAnyOrder
if order does not matter to you.
That's the code for contains
matcher:
public static <E> Matcher<Iterable<? extends E>> contains(List<Matcher<? super E>> itemMatchers) { return IsIterableContainingInOrder.contains(itemMatchers); }
To check tha collection contains items in expected (given) order you can use Hamcrest's containsInRelativeOrder
method.
From javadoc:
Creates a matcher for Iterable's that matches when a single pass over the examined Iterable yields a series of items, that contains items logically equal to the corresponding item in the specified items, in the same relative order For example: assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder("b", "d")).
Actual for Java Hamcrest 2.0.0.0.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With