简体   繁体   English

Mockito 中的错误存根

[英]Wrong stubbing in Mockito

I have the stubbing for the exchange call on a Spring RestTemplate defined as follows:我在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);

To get a predefined response I accept any string, then the GET method, any request entity and a defined response type.为了获得预定义的响应,我接受任何字符串,然后是 GET 方法、任何请求实体和定义的响应类型。

However I do get a PotentialStubbingProblem :但是我确实得到了一个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);

From the exception I see that the expected stubbing is not what I have defined and I cannot figure out why this happens.从异常中我看到预期的存根不是我定义的,我无法弄清楚为什么会发生这种情况。 Doing lenient stubbing here instead does not solve the problem, as it still does not match.在这里做宽松的存根并不能解决问题,因为它仍然不匹配。 Even defining it like follows yields the same result:即使像下面这样定义它也会产生相同的结果:

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

The exchange method on the RestTemplate is overloaded, but with the types being present in the stubbing, this should not pose a problem. RestTemplate上的交换方法已重载,但由于存根中存在类型,这不应该造成问题。 What am I overlooking here?我在这里俯瞰什么?

The stubbing is defined wrong for the exchange method on RestTemplate .对于RestTemplate上的exchange方法,存根定义错误。

The third parameter is not a RequestEntity but a HttpEntity containing the request.第三个参数不是RequestEntity而是包含请求的HttpEntity With this stubbing change the invocation is found.通过此存根更改,可以找到调用。

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

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