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

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


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.Testpublic 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;    }}


IMHO this is much more readable:

people.forEach(person -> Assert.assertThat(person.getGender()), Is.is("male"));


More readable than the approved answer and no separate assertions in a loop:

import static org.assertj.core.api.Assertions.assertThat;assertThat(people).allMatch((person) -> {  return person.gender.equals("male");});