Java 是否有“每个”匹配器的 Hamcrest 断言集合或迭代器的所有元素匹配单个特定匹配器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28860135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a Hamcrest "for each" Matcher that asserts all elements of a Collection or Iterable match a single specific Matcher?
提问by E-Riz
Given a Collection
or Iterable
of items, is there any Matcher
(or combination of matchers) that will assert every item matches a single Matcher
?
给定一个Collection
或Iterable
多个项目,是否有任何Matcher
(或匹配器组合)可以断言每个项目匹配一个Matcher
?
For example, given this item type:
例如,给定此项目类型:
public interface Person {
public String getGender();
}
I'd like to write an assertion that all items in a collection of Person
s have a specific gender
value. I'm thinking something like this:
我想写一个断言,即Person
s集合中的所有项目都具有特定gender
值。我在想这样的事情:
Iterable<Person> people = ...;
assertThat(people, each(hasProperty("gender", "Male")));
Is there any way to do this without writing the each
matcher myself?
有没有办法在不each
自己编写匹配器的情况下做到这一点?
采纳答案by Sotirios Delimanolis
Use the Every
matcher.
使用Every
匹配器。
import org.hamcrest.beans.HasPropertyWithValue;
import org.hamcrest.core.Every;
import org.hamcrest.core.Is;
import org.junit.Assert;
Assert.assertThat(people, (Every.everyItem(HasPropertyWithValue.hasProperty("gender", Is.is("male")))));
Hamcrest also provides Matchers#everyItem
as a shortcut to that Matcher
.
Hamcrest 还提供Matchers#everyItem
了一个快捷方式Matcher
。
Full example
完整示例
@org.junit.Test
public void method() throws Exception {
Iterable<Person> people = Arrays.asList(new Person(), new Person());
Assert.assertThat(people, (Every.everyItem(HasPropertyWithValue.hasProperty("gender", Is.is("male")))));
}
public static class Person {
String gender = "male";
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
回答by Markus
IMHO this is much more readable:
恕我直言,这更具可读性:
people.forEach(person -> Assert.assertThat(person.getGender()), Is.is("male"));