Now we want to add matchers that can be applied when we want to test a book somewhere .. we’re putting them into static methods in a wrapper class so that we’re able to use a static import in our test case later.

One matcher is applied to compare a book’s ISBN number and the other matcher tests the book’s id.

We’re simply subclassing Hamcrest’s TypeSafeMatcherhere – for a full list of the different matchers available, please take a look at API docs.

If you want some more detailed information about this topic I’d recommend the following excellent article from Adrian Elsener posted on planetgeek.ch.

Troubleshooting

It is important to load the Hamcrest dependencies before the JUnit dependencies because JUnit comes with a custom version of Hamcrest .. and this version does not work as intended .. so be careful to use org.hamcrest.MatcherAssert.assertThat instead of org.junit.Assert.assertThat. If you’re using JUnit 4.11 (or above) this shouldn’t be a problem anymore because a newer version of Hamcrest is shipped (1.3 with JUnit 4.11)..

Tutorial Sources

Please feel free to download the tutorial sources from my Bitbucket repository, fork it there or clone it using Mercurial:

hg clone https://bitbucket.org/hascode/hamcrest-matcher-sample

Resources

This entry was posted
on Sunday, October 28th, 2012 at 5:54 pm and is filed under Java, testing.
You can follow any responses to this entry through the RSS 2.0 feed.
You can skip to the end and leave a response. Pinging is currently not allowed.