Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito and Mockito.any(Map.class)

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()?

like image 292
user3254515 Avatar asked Feb 16 '16 15:02

user3254515


People also ask

What is Mockito Any ()?

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.


1 Answers

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.)

like image 184
Jeff Bowman Avatar answered Sep 17 '22 10:09

Jeff Bowman