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

旧街凉风 提交于 2019-11-29 16:34:11

问题


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?


回答1:


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



回答2:


IMHO this is much more readable:

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


来源:https://stackoverflow.com/questions/28860135/is-there-a-hamcrest-for-each-matcher-that-asserts-all-elements-of-a-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!