Java Hamcrest : Collection contains item of type

Marty Pitt picture Marty Pitt · Feb 13, 2011 · Viewed 16.7k times · Source

I'd like to assert that List<Achievement> contains a member of type TestAchievement.

Here's my assertion:

List<Achievement> achievements; // Populated elsewhere
assertThat(achievements,hasItem(isA(TestAchievement.class)));

This doesn't compile, reporting the error:

The method assertThat(T, Matcher) in the type Assert is not applicable for the arguments (List, Matcher<Iterable<TestAchievement>>)

What's the correct syntax for this type of assertion using Hamcrest?

Answer

Marty Pitt picture Marty Pitt · Feb 13, 2011

Thanks for all the help.

The posts here suggested it was a defect with Hamcrest, so I headed over to the hacmrest site to register a bug, whien I discovered that the mvn / ivy dependency declaration I was using was out-of-date, giving me an old version of Hamcrest.

This bug exists with 1.1, which is the latest if declared using

<dependency org="org.hamcrest" name="hamcrest-all" rev="1.1">

However, the correct depedency declaration is:

<dependency org="org.hamcrest" name="hamcrest-library" rev="1.3.RC2"/>

Updating to this solved the issue. The syntax used in my test is:

 assertThat(achievements, hasItem(isA(TestAchievement.class)));