如何使用Hamcrest检查集合是否包含给定顺序的项目

Mar*_*mro 42 java collections hamcrest

如果给定的集合包含给定顺序的给定项目,如何使用Hamcrest进行检查?我试过hasItems但它只是忽略了顺序.

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")); 
Run Code Online (Sandbox Code Playgroud)

And*_*ich 53

您可以使用containsmatcher,但您可能需要使用最新版本的Hamcrest.该方法检查订单.

assertThat(list, contains("foo", "boo"));
Run Code Online (Sandbox Code Playgroud)

containsInAnyOrder如果订单对您无关紧要,您也可以尝试使用.

这是contains匹配器的代码:

  public static <E> Matcher<Iterable<? extends E>> contains(List<Matcher<? super E>> itemMatchers)
  {
    return IsIterableContainingInOrder.contains(itemMatchers);
  }
Run Code Online (Sandbox Code Playgroud)

  • 什么版本的火腿?对我来说,1.3 导致:java.lang.AssertionError: Expected: iterable contains ["foo", "boo"] 但是:不匹配:"bar" (2认同)
  • 该解决方案不适用于结果列表的给定子集,因为contains-Matcher失败,并且未在预期的项目数组中给出任何额外的项目. (2认同)

nnd*_*dru 7

要检查收集包含预期(给定)顺序的项目,您可以使用Hamcrest的containsInRelativeOrder方法.

来自javadoc:

为Iterable创建一个匹配器匹配,当一次传递检查的Iterable产生一系列项目时,它们包含逻辑上等于指定项目中相应项目的项目,具有相同的相对顺序.例如:assertThat(Arrays.asList(" a","b","c","d","e"),containsInRelativeOrder("b","d")).

Java Hamcrest 2.0.0.0的实际值.

希望这可以帮助.