是否有一个Hamcrest Matcher干净地允许我断言,返回对象的Collection的方法的结果至少有一个包含具有特定值的属性的对象?
例如,:
class Person {
private String name;
}测试中的方法返回一个Person集合。我需要断言至少有一个人叫彼得。
发布于 2015-06-20 15:22:18
首先,您需要创建一个与Matcher名称相匹配的Person,然后,您可以使用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")));
}
}https://stackoverflow.com/questions/30955068
复制相似问题