gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:07:27 24 4
gpt4 key购买 nike

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

这会失败,因为剩余的“三”不匹配。

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

关于hamcrest - Hamcrest 的 hasItems、contains 和 containsInAnyOrder 有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33840531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com