是否存在一个“每个”匹配器的Hamcrest,它将一个Collection或Iterable匹配的所有元素断言为一个特定的匹配器?

时间:2015-03-04 16:48:54

标签: java hamcrest

如果有CollectionIterable项,是否有任何Matcher(或匹配器的组合)会断言每个项目与单个Matcher匹配?

例如,给定此项目类型:

public interface Person {
    public String getGender();
}

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

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

如果没有自己编写each匹配器,有没有办法做到这一点?

3 个答案:

答案 0 :(得分:67)

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

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

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