【问题标题】:Mocking a RestTemplate that returns a List in Spring v1.5.14.RELEASE在 Spring v1.5.14.RELEASE 中模拟返回 List 的 RestTemplate
【发布时间】:2019-08-14 14:06:26
【问题描述】:

我有这个我想模拟的 RestTemplate

ResponseEntity<List<Hotel>> deliveryResponse =
                    restTemplate.exchange(link.getHref(),
                            HttpMethod.GET, null, new ParameterizedTypeReference<List<Hotel>>() {
                            });

但我不知道这是否可能。我试过了

when(restTemplate.exchange(eq("delivery"), eq(HttpMethod.GET), any(RequestEntity.class), eq(Object.class)))
                .thenReturn(new ResponseEntity<>(new ParameterizedTypeReference<List<Hotel>>(), HttpStatus.OK));

【问题讨论】:

  • 使用any()而不是any(HttpEntity.class),因为最后一个不包括null

标签: java spring-boot spring-mvc mocking mockito


【解决方案1】:

any(Class)

匹配任何给定类型的对象,不包括空值。


any()

匹配任何内容,包括空值和可变参数。


如前所述,将您的测试代码更改为以下内容将解决您的问题。

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

【讨论】:

  • 我提出的解决方案出现此错误:'ParameterizedTypeReference' 是抽象的;无法实例化
  • 是的,那是一个无法实例化的抽象类。所以你的问题不是关于模拟(不匹配),而是应该如何写返回? -- 也许你可以用ResponseEntity 澄清你到底需要返回什么以及你的代码在做什么?
  • 我已经用模拟替换了 return 值。您可以根据代码的要求定义行为。如果您需要帮助,请随时为您的问题添加更多代码。
猜你喜欢
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 2021-05-02
  • 2019-08-30
  • 1970-01-01
  • 2019-05-28
相关资源
最近更新 更多