JUnit Hamcrest assertion



是否有一个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")));
    }
}

相关内容

最新更新