是否有一个Hamcrest Matcher
可以清楚地让我断言返回对象Collection
的方法的结果至少有一个包含具有特定值的属性的对象?
例如:
class Person {
private String name;
}
被测试的方法返回 Person
的集合。我需要断言,至少有一个人叫彼得。
首先,你需要创建一个可以匹配Person
名称的Matcher
。然后,您可以使用Hamcrest的CoreMatchers#hasItem
来检查Collection
是否具有此数学家匹配的项目。
就我个人而言,我喜欢在static
方法中匿名声明这样的匹配器,作为一种句法加糖:
public class PersonTest {
/** Syntactic sugaring for having a hasName matcher method */
public static Matcher<Person> hasName(final String name) {
return new BaseMatcher<Person>() {
public boolean matches(Object o) {
return ((Person) o).getName().equals(name);
}
public void describeTo(Description description) {
description.appendText("Person should have the name ")
.appendValue(name);
}
};
}
@Test
public void testPeople() {
List<Person> people =
Arrays.asList(new Person("Steve"), new Person("Peter"));
assertThat(people, hasItem(hasName("Peter")));
}
}