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 Person
s 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?
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.
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.
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.
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.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With