如果给定的集合包含给定顺序的给定项目,如何使用 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/