Using Mockito I got in trouble with the following:
Mockito.when(restOperationMock.exchange(
Mockito.anyString(),
Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class),
Mockito.eq(CustomerResponse.class),
**Mockito.anyMap()**)).
thenReturn(re);
The problem was the method wasn't intercepted because I was using Mockito.any(Map.class)
instead of Mockito.anyMap()
and I was passing as a parameter a HashMap
. What are the differences between Mockito.any(Map.class)
and Mockito.anyMap()
?
Mockito allows us to create mock objects and stub the behavior for our test cases. We usually mock the behavior using when() and thenReturn() on the mock object.
There is only one small difference between any(Map.class)
and anyMap()
: Starting with Mockito 2.0, Mockito will treat the any(Map.class)
call to mean isA(Map.class)
rather than ignoring the parameter entirely. (See the comment from Mockito contributor Brice on this SO answer.) Because restOperationMock.exchange
takes an Object vararg, you may need anyMap
to catch a case where a non-Map object is being passed, or no object at all is passed.
(I'd previously put that as a "dummy value" to return, Mockito can return an empty Map for calls to anyMap()
, but can only return a null
for calls to any(Map.class)
. If restOperationMock.exchange
delegates to a real implementation during stubbing, such as if it were a spy or unmockable method (final method, method on a final class, etc), then that dummy value may be used in real code. However, that's only true for any()
; anyMap()
and any(Map.class)
both give Mockito enough information to return a dummy Map implementation, where any()
has its generics erased and only knows enough to return null
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With