Issue
I have a generic method which invokes specified URL using RestTemplate.exchange
. Method itself is working and loading data fine but I am not able to unit test it using Mockito.
Main Method
@Service
public class MyClass{
private <T> List<T> loadData(String url) {
return restTemplate.exchange(
url, GET, null, new ParameterizedTypeReference<List<T>>(){}
).getBody().stream().collect(toList()));
}
}
Unit Test
@Runwith(MockitoJUnitRunner.class)
public class MyTest {
@Mock
private RestTemplate restTemplate;
@Test
public void givenCall_myMethod_WillReturnData(){
given(restTemplate.exchange(
ArgumentMatchers.anyString(), ArgumentMatchers.any(), any(), any(Class.class)
))
.willReturn(bodyData());
}
}
If I use non-generic version then everything works fine, however mockito returns NullPointerException
with generics version.
What's wrong or missing?
Solution
The last wildcard you have defined as: any(Class.class)
.
The exchange method has signature:
exchange(String url,
HttpMethod method,
HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType) throws RestClientException
You should define it as: any(ParameterizedTypeReference.class)
Also I would suggest replacing the very vague any()
set-us with a any(Class)
equivalents.
Answered By - Maciej Kowalski
Answer Checked By - Cary Denson (JavaFixing Admin)