Hamcrest 的 hasItems、contains 和 containsInAnyOrder 有何不同?

How do Hamcrest's hasItems, contains and containsInAnyOrder differ?

Hamcrest 提供了许多匹配器来断言集合的内容。所有这些案例都通过了:

Collection<String> c = ImmutableList.of("one", "two", "three");
assertThat(c, hasItems("one", "two", "three");
assertThat(c, contains("one", "two", "three");
assertThat(c, containsInAnyOrder("one", "two", "three");

hasItemscontainscontainsInAnyOrder 有何不同?

hasItems checks:

consecutive passes over the examined Iterable yield at least one item that is equal to the corresponding item from the specified items.

也就是说,它确保集合包含至少 这些项目,任何顺序。所以,

assertThat(c, hasItems("one", "two"));

也会通过,多余的项目将被忽略。并且:

assertThat(c, hasItems("three", "two", "one"));

也会通过。

contains checks:

a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items.

因此它确保该集合包含恰好 这些项目:

assertThat(c, contains("one", "two")); // Fails

这会失败,因为剩余的 "three" 不匹配。

assertThat(c, contains("three", "two", "one")); // Fails

这失败了,因为相应的项目不匹配。

另一个相关的匹配器,containsInAnyOrderchecks 正是这些项目存在,但顺序不限:

Creates an order agnostic matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to one item anywhere in the specified items.

缺少项目的测试失败:

assertThat(c, containsInAnyOrder("one", "two")); // Fails

但不同顺序的所有项目都会通过:

assertThat(c, containsInAnyOrder("three", "two", "one"));