是否存在“每个”的“Hamcrest”。 Matcher声明Collection或Iterable的所有元素匹配单个特定匹配器? [英] Is there a Hamcrest "for each" Matcher that asserts all elements of a Collection or Iterable match a single specific Matcher?

查看:127
本文介绍了是否存在“每个”的“Hamcrest”。 Matcher声明Collection或Iterable的所有元素匹配单个特定匹配器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定 Collection Iterable 项目,是否有匹配(或匹配器的组合)将声明每个项目匹配单个匹配器

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

如果没有写每个,有没有办法做到这一点 matcher我自己?

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

推荐答案

使用 每个 匹配器。

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还提供 Matchers#everyItem 作为匹配。

Hamcrest also provides Matchers#everyItem as a shortcut to that 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;
    }
}

这篇关于是否存在“每个”的“Hamcrest”。 Matcher声明Collection或Iterable的所有元素匹配单个特定匹配器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆