Java 是否有“每个”匹配器的 Hamcrest 断言集合或迭代器的所有元素匹配单个特定匹配器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28860135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:57:46  来源:igfitidea点击:

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

javahamcrest

提问by E-Riz

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

给定一个CollectionIterable多个项目,是否有任何Matcher(或匹配器组合)可以断言每个项目匹配一个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 gendervalue. I'm thinking something like this:

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

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

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

有没有办法在不each自己编写匹配器的情况下做到这一点?

采纳答案by Sotirios Delimanolis

Use the Everymatcher.

使用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 also provides Matchers#everyItemas a shortcut to that Matcher.

Hamcrest 还提供Matchers#everyItem了一个快捷方式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;
    }
}

回答by Markus

IMHO this is much more readable:

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

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