Java 使用Hamcrest检查集合中是否有某些元素
我正在尝试测试代码,我希望一个集合有三个特定值中的两个。有没有一种简洁的方法可以用Hamcrest 1.3测试这一点 我想要这样的东西:Java 使用Hamcrest检查集合中是否有某些元素,java,hamcrest,Java,Hamcrest,我正在尝试测试代码,我希望一个集合有三个特定值中的两个。有没有一种简洁的方法可以用Hamcrest 1.3测试这一点 我想要这样的东西: Collection<String> set = new HashSet<>(); set.add("A"); set.add("B"); set.add("C"); // Remove an indeterminate element set.iterator().next().remove(); // What the match
Collection<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
// Remove an indeterminate element
set.iterator().next().remove();
// What the matcher actually is is the question
assertThat(set, hasSomeOf("A", "B", "C"));
assertThat(set, hasSize(2));
这也有一个缺点,我不能使用额外的匹配,我希望在我的真实情况。(为了重用我虚构的matcher,我想做一些类似于hasSome(startsWith(“A”)、startsWith(“B”)、startsWith(“C”)
澄清
如果
set
在hasSomeOf
的参数中不包含某些内容,则匹配器将失败。我相信您正在寻找的匹配器是everyItem()
与oneOf()
或anyOf()
结合使用的。对于hasSome(“A”、“B”、“C”),场景[“C”、“H”
应该失败
,可以按如下方式编写:
assertThat(set,everyItem(是(“A”、“B”、“C”)之一);
当添加项目H
时,将导致以下故障:
Expected: every item is is one of {"A", "B", "C"}
but: an item was "H"
对于您希望包含多个匹配器的其他场景,您可以简单地替换期望值
assertThat(set,everyItem(是(任何一个)(startsWith(“A”)、startsWith(“B”)、startsWith(“C”));
这将导致:
Expected: every item is is (a string starting with "A" or a string starting with "B" or a string starting with "C")
but: an item was "H"
我相信您正在寻找的匹配者是
everyItem()
与oneOf()
或anyOf()
结合使用。对于hasSome(“A”、“B”、“C”)
,场景[“C”、“H”]
应该失败,可以编写如下:
assertThat(set,everyItem(是(“A”、“B”、“C”)之一);
当添加项目H
时,将导致以下故障:
Expected: every item is is one of {"A", "B", "C"}
but: an item was "H"
对于您希望包含多个匹配器的其他场景,您可以简单地替换期望值
assertThat(set,everyItem(是(任何一个)(startsWith(“A”)、startsWith(“B”)、startsWith(“C”));
这将导致:
Expected: every item is is (a string starting with "A" or a string starting with "B" or a string starting with "C")
but: an item was "H"
难道你不想创建像hasSome(Matcher countMatcher,Matcher…matchers)这样的东西,然后像hasSome(等于(2),hasItem(“A”),hasItem(“B”),hasItem(“C”)那样调用它吗?我把第一个参数也留作Matcher,因为它允许你拥有比细节更少/更多的东西。如果
集={“C”,“H”}
?检查hasSomeOf(“A”、“B”、“C”)
将为真,检查hasSize(2)
将为真,但这并不保证集合“有三个特定值中的两个”。我的隐含语义(可能更清楚)是[“C”、“H”]
将失败hasSome(“A”、“B”、“C”)
你不想创建类似hasSome(Matcher countMatcher,Matcher…matchers)的东西,然后像hasSome(equals(2)、hasItem(“A”)、hasItem(“B”)、hasItem(“C”)那样调用它吗?我把第一个参数也留作Matcher,因为它允许你拥有比细节更少/更多的东西。如果set={“C”,“H”}
?检查hasSomeOf(“A”、“B”、“C”)
将为真,检查hasSize(2)
将为真,但它不能保证集合“有三个特定值中的两个”。我的隐含语义(可能更清楚)是[“C”、“H”]
将失败hasSome(“A”、“B”、“C”)