gpt4 book ai didi

java - Hamcrest Matchers.contains 匹配器不工作(?)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:04:53 24 4
gpt4 key购买 nike

我正在尝试测试一个集合是否有一个 toString() 方法返回特定字符串的项目。我尝试使用优秀的 Hamcrest 匹配类,通过将包含与 Matchers.hasToString 结合使用,但不知何故,它的 Matchers.contains 无法匹配项目,即使它存在于集合中。

这是一个例子:

class Item {

private String name;

public Item(String name){
this.name = name;
}

public String toString(){
return name;
}
}

// here's a sample collection, with the desired item added in the end
Collection<Item> items = new LinkedList<Item>(){{
add(new Item("a"));
add(new Item("b"));
add(new Item("c"));
}};

Assert.assertThat(items, Matchers.contains(Matchers.hasToString("c")));

以上断言不成功。消息如下:

java.lang.AssertionError: 
Expected: iterable containing [with toString() "c"]
but: item 0: toString() was "a"
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.junit.Assert.assertThat(Assert.java:865)
at org.junit.Assert.assertThat(Assert.java:832)

看起来 Matchers.contains 匹配器试图遍历列表,但 Matchers.hasToString 匹配器在第一项中失败并使迭代的其余部分无效。 Matchers.contains 的 Hamcrest javadoc 说:

“为 Iterables 创建一个匹配器,当单次遍历被检查的 Iterable 产生满足指定匹配器的单个项目时匹配。对于正匹配,被检查的 iterable 必须只产生一个项目”

我做错了什么吗?

最佳答案

我认为您正在寻找 Matchers.hasItem(..)

Assert.assertThat(items, Matchers.hasItem(Matchers.hasToString("c")));

哪个州

Creates a matcher for Iterables that only matches when a single pass over the examined Iterable yields at least one item that is matched by the specified itemMatcher. Whilst matching, the traversal of the examined Iterable will stop as soon as a matching item is found.

Matchers.contains,如您所述,

Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a single item that satisfies the specified matcher. For a positive match, the examined iterable must only yield one item.

在我看来,这好像是说 Iterable 中应该只有一个元素。

关于java - Hamcrest Matchers.contains 匹配器不工作(?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22720233/

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