Is there a Hamcrest “for each” Matcher that asserts all elements of a Collection or Iterable match a single specific Matcher?

后端 未结 2 552
渐次进展
渐次进展 2021-01-01 08:06

Given a Collection or Iterable of items, is there any Matcher (or combination of matchers) that will assert every item matches a singl

相关标签:
2条回答
  • 2021-01-01 08:49

    Use the Every matcher.

    import org.hamcrest.beans.HasPropertyWithValue;
    import org.hamcrest.core.Every;
    import org.hamcrest.core.Is;
    import org.junit.Assert;
    
    Assert.assertThat(people, (Every.everyItem(HasPropertyWithValue.hasProperty("gender", Is.is("male")))));
    

    Hamcrest also provides Matchers#everyItem as a shortcut to that Matcher.


    Full example

    @org.junit.Test
    public void method() throws Exception {
        Iterable<Person> people = Arrays.asList(new Person(), new Person());
        Assert.assertThat(people, (Every.everyItem(HasPropertyWithValue.hasProperty("gender", Is.is("male")))));
    }
    
    public static class Person {
        String gender = "male";
    
        public String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            this.gender = gender;
        }
    }
    
    0 讨论(0)
  • 2021-01-01 08:51

    IMHO this is much more readable:

    people.forEach(person -> Assert.assertThat(person.getGender()), Is.is("male"));
    
    0 讨论(0)
提交回复
热议问题