Issue
I have this RestTemplate that I want to mock
ResponseEntity<List<Hotel>> deliveryResponse =
restTemplate.exchange(link.getHref(),
HttpMethod.GET, null, new ParameterizedTypeReference<List<Hotel>>() {
});
but I don't know if it is possible. I've tried
when(restTemplate.exchange(eq("delivery"), eq(HttpMethod.GET), any(RequestEntity.class), eq(Object.class)))
.thenReturn(new ResponseEntity<>(new ParameterizedTypeReference<List<Hotel>>(), HttpStatus.OK));
Solution
Matches any object of given type, excluding nulls.
Matches anything, including nulls and varargs.
So as previously suggested changing your test code to the following will solve your issue.
As ParameterizedTypeReference
can not be instantiated because it is an abstract class, you could return a mock instead and define the needed behaviour on it.
List<Hotel> hotels = new ArrayList<>();
ResponseEntity response = Mockito.mock(ResponseEntity.class);
Mockito.when(response.getStatusCode()).thenReturn(HttpStatus.OK);
Mockito.when(response.getBody()).thenReturn(hotels);
when(restTemplate.exchange(eq("delivery"), eq(HttpMethod.GET), any(), eq(Object.class)))
.thenReturn(response);
Answered By - second
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)