More readable and typeable…

Hamcrest allows you to write readable constraints, which for example can be used with an assert statement. Hamcrest is included since JUnit 4.4 and it is the first time that third-party classes have been included in JUnit. But when you play around with Hamcrest and the assertThat statement you don’t want go back to old complex and unreadable assert statements.

JUnit and assertThat

With Hamcrest it’s very easy to write readable assert statements in a JUnit test case . In the following example we want to check if a person is older than 21 years.

import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;

...

Person person1 = new Person();
person1.setName("Bob");
person1.setAge(22);

assertThat(person1.getAge(), greaterThan(21));

As you can see the assert statement is pretty straightforward. The second parameter of an assertThat statement is a Matcher which evaluates if the first parameter is greater than the integer value from the Matcher. This syntax allows you to think in terms of subject, verb, object and not in assertEquals.

Hamcrest uses Matcher which are responsible to evaluate a given statement. A good overview about Hamcrest is the official tutorial.

JUnit currently ships with a few matchers, defined in org.hamcrest.CoreMatchers and org.junit.matchers.JUnitMatchers. To use the other matchers download the hamcrest-all.*.jar library.

hamcrest-collections

hamcrest-collections implements features such as select, reject, map, reduce and zip which can be used on collections. This is a useful library which uses Hamcrest to operate on collections.

The following example show how to select from a List of integers all numbers between 5 and 9.

import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrestcollections.Selector.*;

...

List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i <= 10; i++) {
	numbers.add(i);
}

Iterable<Integer> items = select(numbers, allOf(greaterThan(5), lessThan(9)));

System.out.println(items);

Which genearte the following output:

[6, 7, 8]

Further reading...

A good starting point as already mention is the official Hamcrest Homepage.

I forgot to mention that there is also the logicalpractice-collections library, which you can use on collections in a more sophisticated way than hamcrest-collections.

http://code.google.com/p/logicalpractice-collections/

*name

*e-mail

web site

leave a comment


 
  • Disclaimer

    This is a personal weblog. The opinions expressed here represent my own and not those of my employer.