【问题标题】:Wrong stubbing in MockitoMockito 中的错误存根
【发布时间】:2021-04-29 11:38:16
【问题描述】:

我在Spring RestTemplate 上的交换电话存根定义如下:

    Class<String> dummyResponseType = String.class;
    ResponseEntity dummyResponse = mock(ResponseEntity.class);
    given(dummyResponse.getBody()).willReturn("Hello world");
    HttpHeaders responseHeaders = new HttpHeaders();
    String returnedCorrelationId = UUID.randomUUID().toString();
    responseHeaders.add(HttpHeaderConstants.CORRELATION_ID, returnedCorrelationId);
    given(dummyResponse.getHeaders()).willReturn(responseHeaders);

    given(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(RequestEntity.class), eq(dummyResponseType))).willReturn(dummyResponse);

为了获得预定义的响应,我接受任何字符串,然后是 GET 方法、任何请求实体和定义的响应类型。

但是我确实收到了PotentialStubbingProblem

org.mockito.exceptions.misusing.PotentialStubbingProblem: 
Strict stubbing argument mismatch. Please check:
 - this invocation of 'exchange' method:
    restTemplate.exchange(
    "http://localhost:8080//api/ping",
    GET,
    <java.lang.Object@3b152928,[X-Correlation-Id:"00e2ab7c-808e-4e1c-b3a9-d65eff7b37ca", Authorization:"Bearer authToken"]>,
    class java.lang.String
);
    -> at 
 - has following stubbing(s) with different arguments:
    1. restTemplate.exchange("", null, null, null);

从异常中我看到预期的存根不是我定义的,我无法弄清楚为什么会发生这种情况。在这里做宽松的存根并不能解决问题,因为它仍然不匹配。即使像下面这样定义它也会产生相同的结果:

given(restTemplate.exchange(anyString(), any(HttpMethod.class), any(RequestEntity.class), any(Class.class))).willReturn(dummyResponse);

RestTemplate 上的交换方法已重载,但由于存根中存在类型,这不会造成问题。 我在这里俯瞰什么?

【问题讨论】:

    标签: java spring mockito resttemplate


    【解决方案1】:

    RestTemplate 上的 exchange 方法的存根定义错误。

    第三个参数不是RequestEntity,而是包含请求的HttpEntity。通过此存根更改,找到调用。

    【讨论】:

      猜你喜欢
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2011-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多