【问题标题】:JUnit Hamcrest assertionJUnit Hamcrest 断言
【发布时间】:2015-06-20 14:29:25
【问题描述】:

是否有一个 Hamcrest Matcher 可以让我清楚地断言,返回 Collection 对象的方法的结果至少有一个对象包含具有特定值的属性?

例如:

class Person {
   private String name;
}

被测方法返回Person 的集合。 我需要断言至少有一个人叫彼得。

【问题讨论】:

    标签: java junit junit4 hamcrest


    【解决方案1】:

    首先,您需要创建一个可以匹配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")));
        }
    }
    

    【讨论】:

    • 完美的解释。谢谢!
    • 您甚至可以使用hasProperty 匹配器以避免编写hasName 匹配器:assertThat(people, hasItem(hasProperty("name", equalTo("Peter"))));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    相关资源
    最近更新 更多