有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JUnit Hamcrest断言

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

例如:

class Person {
   private String name;
}

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


共 (1) 个答案

  1. # 1 楼答案

    首先,需要创建一个^{}来匹配Person的名称。然后,您可以使用hamcrest的^{}来检查Collection是否有与此mathcer匹配的项

    就我个人而言,我喜欢在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")));
        }
    }