Mockito Matcher vs Hamcrest Matcher?

It will be easy, but I can not find the difference between them and which one to use if I have lib included in my classpath?

+26
java mockito hamcrest
Dec 01 2018-11-12T00:
source share
1 answer

The matcrest methods returned by the matcher return Matcher<T> , and the Mockito matches 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 .

This means that you can only use Hamcrest adapters if a Matcher<?> Object is expected in the signature, usually in assertThat . When setting up expectations or checks, when you call the methods of the mock object, you use the mockito mock.

For example (with full names for clarity):

 @Test public void testGetDelegatedBarByIndex() { Foo mockFoo = mock(Foo.class); // inject our mock objectUnderTest.setFoo(mockFoo); Bar mockBar = mock(Bar.class); when(mockFoo.getBarByIndex(org.mockito.Matchers.any(Integer.class))). thenReturn(mockBar); Bar actualBar = objectUnderTest.getDelegatedBarByIndex(1); assertThat(actualBar, org.hamcrest.Matchers.any(Bar.class)); verify(mockFoo).getBarByIndex(org.mockito.Matchers.any(Integer.class)); } 

If you want to use the Hamcrest match in a context that requires a Mockito binder, you can use the org.mockito.Matchers.argThat match. It converts a Hamcrest match to a Mockito match. So, let's say you wanted to match the double value with some precision (but not so much). In this case, you can do:

 when(mockFoo.getBarByDouble(argThat(is(closeTo(1.0, 0.001))))). thenReturn(mockBar); 
+69
Dec 02 2018-11-11T00:
source share



All Articles