Mockito’s Matcher vs Hamcrest Matcher?

Hamcrest matcher methods return Matcher<T> and Mockito matchers return T. So, for example: org.hamcrest.Matchers.any(Integer.class) returns an instance of org.hamcrest.Matcher<Integer>, and org.mockito.Matchers.any(Integer.class) returns an instance of Integer. That means that you can only use Hamcrest matchers when a Matcher<?> object is expected in the signature – typically, in assertThat calls. When setting up expectations or verifications … Read more

How do I assert an Iterable contains elements with a certain property?

Thank you @Razvan who pointed me in the right direction. I was able to get it in one line and I successfully hunted down the imports for Hamcrest 1.3. the imports: import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.contains; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; the code: assertThat( myClass.getMyItems(), contains( hasProperty(“name”, is(“foo”)), hasProperty(“name”, is(“bar”)) ));

Hamcrest compare collections

If you want to assert that the two lists are identical, don’t complicate things with Hamcrest: assertEquals(expectedList, actual.getList()); If you really intend to perform an order-insensitive comparison, you can call the containsInAnyOrder varargs method and provide values directly: assertThat(actual.getList(), containsInAnyOrder(“item1”, “item2”)); (Assuming that your list is of String, rather than Agent, for this example.) If … Read more

Getting “NoSuchMethodError: org.hamcrest.Matcher.describeMismatch” when running test in IntelliJ 10.5

Make sure the hamcrest jar is higher on the import order than your JUnit jar. JUnit comes with its own org.hamcrest.Matcher class that is probably being used instead. You can also download and use the junit-dep-4.10.jar instead which is JUnit without the hamcrest classes. mockito also has the hamcrest classes in it as well, so … Read more