Using Hamcrest Matchers.everyItem
For my Junit test I wanted to make use of Matchers.everyItem so I could easily check if every item of a list machtes a certain matcher. Resulting in a small line of code which is nice to read.
assertThat(itemResults, everyItem(Matchers.<ItemResult>hasProperty("score", is(new Double(1.0)))));
The everyItem machter is available in hamcrest 1.2 so an easy update would do the trick. And of course it doesn’t. The project had a dependency on hamcrest-all 1.1. Unfortunately there is no 1.2 version. After some searching I could use the hamcrest-integration 1.2.1 (which depends on core and library).
This upgrade resulted in a few compile errors. For example:
hasItems(is(ownerId1), is(ownerId2))); // should be: Matchers.<String>hasItems(is(ownerId1), is(ownerId2))); // and assertThat(object, is(ArrayList.class)); // should be: assertThat(object, Matchers.<Object>instanceOf(ArrayList.class));
When running the test I’ve got a NoSuchMethodException. Which is cause by conflicting classes in the Junit 4.8.2 jar. For some reason they added Hamcrest classes version 1.1 to the jar.
This can be fixed by using artifactId junit-dep instead of junit and add an exclusion to prevent maven to fetch the 1.1 version of the hamcrest-core. (See the maven snippet below.)
Enjoy using junit and hamcrest!
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit-dep</artifactId> <version>4.8.2</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-integration</artifactId> <version>1.2.1</version> <scope>test</scope> </dependency> </dependencies>