Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hamcrest

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?

like image 515
E-Riz Avatar asked Mar 04 '15 16:03

E-Riz


People also ask

What is a Hamcrest matcher?

Hamcrest is a framework that assists writing software tests in the Java programming language. It supports creating customized assertion matchers ('Hamcrest' is an anagram of 'matchers'), allowing match rules to be defined declaratively. These matchers have uses in unit testing frameworks such as JUnit and jMock.

Why are there Hamcrest matchers?

Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.

What is the Hamcrest matcher to test if a string contains another string?

Class StringContains. Tests if the argument is a string that contains a substring. Creates a matcher that matches if the examined String contains the specified String anywhere.

What is Hamcrest in Python?

Introduction. PyHamcrest is a framework for writing matcher objects, allowing you to declaratively define "match" rules. There are a number of situations where matchers are invaluable, such as UI validation, or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used.


1 Answers

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;     } } 
like image 160
Sotirios Delimanolis Avatar answered Sep 22 '22 11:09

Sotirios Delimanolis