简体   繁体   中英

Mocking a RestTemplate that returns a List in Spring v1.5.14.RELEASE

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

any(Class)

Matches any object of given type, excluding nulls.


any()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM