给定一个Collection或Iterable项,是否有任何Matcher(或匹配项的组合)断言每个项都匹配一个Matcher?
Collection
Iterable
Matcher
例如,给定此项目类型:
public interface Person { public String getGender(); }
我想写一个断言,表示Persons 集合中的所有项目都具有特定gender值。我在想这样的事情:
Person
gender
Iterable<Person> people = ...; assertThat(people, each(hasProperty("gender", "Male")));
没有each自己写匹配器,有什么办法吗?
each
使用Every匹配器。
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还提供Matchers#everyItem了一种快捷方式Matcher。
Matchers#everyItem
完整的例子
@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; } }