如果有Collection
或Iterable
项,是否有任何Matcher
(或匹配器的组合)会断言每个项目与单个Matcher
匹配?
例如,给定此项目类型:
public interface Person {
public String getGender();
}
我想写一个断言,Person
集合中的所有项都有一个特定的gender
值。我在想这样的事情:
Iterable<Person> people = ...;
assertThat(people, each(hasProperty("gender", "Male")));
如果没有自己编写each
匹配器,有没有办法做到这一点?
答案 0 :(得分:67)
使用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
的快捷方式。
完整示例
@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;
}
}
答案 1 :(得分:1)
恕我直言,这更具可读性:
people.forEach(person -> Assert.assertThat(person.getGender()), Is.is("male"));
答案 2 :(得分:0)
比批准的答案更具可读性,并且循环中没有单独的断言:
import static org.assertj.core.api.Assertions.assertThat;
assertThat(people).allMatch((person) -> {
return person.gender.equals("male");
});