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

JavaHamcrest

Java Problem Overview


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

For example, given this item type:

public interface Person {
    public String getGender();
}

I'd like to write an assertion that all items in a collection of Persons have a specific gender value. I'm thinking something like this:

Iterable<Person> people = ...;
assertThat(people, each(hasProperty("gender", "Male")));

Is there any way to do this without writing the each matcher myself?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

IMHO this is much more readable:

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

Solution 3 - Java

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");
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionE-RizView Question on Stackoverflow
Solution 1 - JavaSotirios DelimanolisView Answer on Stackoverflow
Solution 2 - JavaMarkusView Answer on Stackoverflow
Solution 3 - JavaxaviertView Answer on Stackoverflow