I have the following method invocation in my class under test:
class ClassUnderTest {
[...]
restTemplate.getForEntity(url, MyResponseEntity.class, parameterMap);
[...]
}
In the unit test of the class containing this line, I want to stub the getForEntity
method such that it returns different responses for different entries in the parameterMap
.
Using BDDMockito, I'm trying to match that the desired parameter is part of the parameterMap by using argThat
:
@InjectMocks
private ClassUnderTest classUnderTest;
@Mock
private RestTemplate restTemplate;
[...]
given(restTemplate.getForEntity(anyString(), any(Class.class), argThat(hasEntry("myKey", "myValue"))
.willReturn(responseEntityA);
However, if I run the test such that the parameterMap
contains (I verified this in the debugger) a key "myKey" and a value "myValue", I get a NullPointerException
, because mockito does not seem to be able to match the method call with the stub I created.
On the other hand, using the following very general matching allows me run my tests without NPE, by providing a default response for all calls, however it does not allow me to define a custom response for a given parameter.
given(restTemplate.getForEntity(anyString(), any(Class.class), anyMap())
.willReturn(defaultResponseEntity);
What is the reason for this? Does argThat
only work for methods with a single parameter?
Is there another way to match calls of the getEntity
with a map that contains a certain (key, value) pair?