【问题标题】:Getting null pointer on response when trying to mock rest template尝试模拟休息模板时在响应中获取空指针
【发布时间】:2021-04-29 04:19:59
【问题描述】:

我试图在单元测试中使用 mockito 来模拟下面的 rest 调用。

  String url = baseUrl  + "/samples";

  ResponseEntity<SampleDto> response =
                restTemplate.exchange(url, HttpMethod.GET, null, SampleDto.class);

及其模拟使用:

  when(restTemplate.exchange(eq(anyString()),eq(HttpMethod.GET), null,
            eq(SampleDto.class))).thenReturn(new ResponseEntity<>(new SampleDto(), HttpStatus.OK));

response 一直为空。有什么建议吗?

【问题讨论】:

  • 为什么要模拟restTemplate?你可以使用 MockMVC 来模拟控制器的使用
  • 这是我想模拟的一些额外的 REST 调用。
  • 好的,你可以使用 WireMock 进行 REST 调用 example
  • 这是用于测试用例的,所以我不想为此使用wiremock。我希望这是一个公平的场景,所以只想完成这项工作
  • 对于您在交换参数中的案例问题,Mockito 无法匹配(eq(anyString()),eq(HttpMethod.GET), null, eq(SampleDto.class)。如果您将所有参数更改为any(),这应该可以工作。

标签: spring unit-testing mockito


【解决方案1】:

请尝试以下配置

  when(restTemplate.exchange(Mockito.anyString()
                , Mockito.eq(HttpMethod.GET)
                , null
                , Mockito.<Class<SampleDto>>any())
   ).thenReturn(new ResponseEntity<>(new SampleDto(), HttpStatus.OK));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-30
    • 2021-06-24
    • 2021-02-27
    • 2021-08-16
    • 2020-04-07
    • 2018-12-08
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多