19

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

fawaad
  • 341
  • 6
  • 12
fernando1979
  • 1,727
  • 2
  • 20
  • 26

1 Answers1

22

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

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251