是否有一个 Hamcrest "for each" Matcher 断言 Collection 或 Iterable 的所有元素都匹配一个特定的 Matcher?

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

给定 CollectionIterable 项,是否有任何 Matcher(或匹配器的组合)断言每个项都匹配单个 Matcher

例如,给定此项目类型:

public interface Person {
    public String getGender();
}

我想写一个断言,即 Person 集合中的所有项目都具有特定的 gender 值。我在想这样的事情:

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

有没有办法不用自己编写 each 匹配器来做到这一点?

使用 Every 匹配器。

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 还提供 Matchers#everyItem 作为 Matcher 的快捷方式。


完整示例

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

恕我直言,这更具可读性:

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

比已批准的答案更具可读性,并且循环中没有单独的断言:

import static org.assertj.core.api.Assertions.assertThat;

assertThat(people).allMatch((person) -> {
  return person.gender.equals("male");
});