简体   繁体   English

模拟在Spring v1.5.14.RELEASE中返回列表的RestTemplate

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

I have this RestTemplate that I want to mock 我有这个要模拟的RestTemplate

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. 匹配任何给定类型的对象,不包括null。


any()

Matches anything, including nulls and varargs. 匹配任何内容,包括null和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. 由于ParameterizedTypeReference是抽象类,因此无法实例化,因此可以返回一个模拟并在其上定义所需的行为。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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