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);
jhericks Dec 02 2018-11-11T00: 00Z
source share