Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if collection contains items in given order using Hamcrest

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"));  
like image 742
Mariusz Jamro Avatar asked Mar 25 '13 06:03

Mariusz Jamro


People also ask

What is the Hamcrest matcher to test if a string contains another string?

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.

Is Hamcrest a matcher?

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() .

What is matcher in JUnit?

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.


2 Answers

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);   } 
like image 161
Andrey Adamovich Avatar answered Sep 18 '22 12:09

Andrey Adamovich


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.

like image 43
nndru Avatar answered Sep 21 '22 12:09

nndru