I’ve seen Matchers used in EasyMock but I kinda stumbled across the assertThat method in JUnit today and realised how powerful this stuff can be.
Usage:
assertThat(“You Failed”, testValue, allOff(greaterThan(3), lessThan(6))
They seem a lot simpler in this context even though they are the same thing.
The Matchers are taken from a project called Hamcrest which both JUnit, various xMock and other testing frameworks have all jumped on board to.
Hamcrest comes with a library of useful matchers. Here are some of the most important ones.
- Core
- anything – always matches, useful if you don’t care what the object under test is
- describedAs – decorator to adding custom failure description
- is – decorator to improve readability – see “Sugar”, below
- Logical
- allOf – matches if all matchers match, short circuits (like Java &&)
- anyOf – matches if any matchers match, short circuits (like Java ||)
- not – matches if the wrapped matcher doesn’t match and vice versa
- Object
- equalTo – test object equality using Object.equals
- hasToString – test Object.toString
- instanceOf, isCompatibleType – test type
- notNullValue, nullValue – test for null
- sameInstance – test object identity
- Beans
- hasProperty – test JavaBeans properties
- Collections
- array – test an array’s elements against an array of matchers
- hasEntry, hasKey, hasValue – test a map contains an entry, key or value
- hasItem, hasItems – test a collection contains elements
- hasItemInArray – test an array contains an element
- Number
- closeTo – test floating point values are close to a given value
- greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo – test ordering
- Text
- equalToIgnoringCase – test string equality ignoring case
- equalToIgnoringWhiteSpace – test string equality ignoring differences in runs of whitespace
- containsString, endsWith, startsWith – test string matching
Here is a summary of Matchers from the Hamcrest tutorial page. They may not all be in JUnit. JUnit ships with org.hamcrest.CoreMatchers
and org.junit.matchers.JUnitMatchers.
Assumptions
Assumptions are like @Ignore-ing tests programmatically. They are a test, intended to determine that the environment a test is running in, will successfully run the test. The example from the JUnit 4.4 release notes best illustrates this:
import static org.junit.Assume.*
@Test public void filenameIncludesUsername() { assumeThat(File.separatorChar, is('/')); assertThat(new User("optimus").configFileName(),
is("configfiles/optimus.cfg")); }
If the expression in the assume statement fails, then the test will be marked as passed. Apparently in future, the failed assumption may lead to the test being marked as ignored which would be excellent.
Edit: Another useful resource is the Junit API on Matchers