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

自古美人都是妖i 提交于 2019-11-30 05:36:27

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.

Evgeniy Dorofeev

You need to implement a custom Matcher, something like this

class ListMatcher extends BaseMatcher {
    String[] items;

    ListMatcher(String... items) {
        this.items = items;
    }

    @Override
    public boolean matches(Object item) {
        List list = (List) (item);
        int l = -1;
        for (String s : items) {
            int i = list.indexOf(s);
            if (i == -1 || i < l) {
                return false;
            }
            l = i;
        }
        return true;
    }

    @Override
    public void describeTo(Description description) {
        // not implemented
    }
}

@Test
public void test1() {
    List<String> list = Arrays.asList("foo", "bar", "boo");
    Assert.assertThat(list, new ListMatcher("foo", "boo"));
    Assert.assertThat(list, new ListMatcher("boo", "foo"));
}

The accepted answer is not working for me. It still fails, saying

Expected: iterable containing ["foo", "boo"] but: Not matched: "bar"

So I wrote my own IsIterableContainingInRelativeOrder, and submitted it as a patch.

Andreas Guther

I found a solution at http://www.baeldung.com/hamcrest-collections-arrays

Look for the section that has an example with strict order.

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, contains("ab", "cd", "ef"));

Basically you need to use the contains Matcher (org.hamcrest.Matchers.contains)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!