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

标签 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")); 

最佳答案

您可以改用 contains 匹配器,但您可能需要使用最新版本的 Hamcrest。该方法检查订单。

assertThat(list, contains("foo", "boo"));

如果顺序对您不重要,您也可以尝试使用 containsInAnyOrder

这是 contains 匹配器的代码:

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

关于java - 如何使用 Hamcrest 检查集合是否包含给定顺序的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15609132/

相关文章:

java - 当方向改变时,如何在 GridView 中保存位图图像的状态?

java - 从 pkcs12 和文本加密中提取私钥

java - core-ktx 1.7.0 和 Hilt

json - 使用 Hamcrest 和 JsonPath : How count the body size? 的 Spring MVC 测试(不计算成员)

java - 如何通过子类访问父类变量

java - Collections.sort() 不适用于自定义对象

java - HashBiMap 是线程安全的吗?

java - 为什么 Collections.synchronizedList(list) 在内部使用 instanceof 检查?

Eclipse:无法解析类型 org.hamcrest.core.CombinableMatcher$CombinableBothMatcher。它是从所需的 .class 文件间接引用的

scala - 规范 2:使用 Hamcrest 匹配器