簡體   English   中英

Mockito 中的錯誤存根

[英]Wrong stubbing in Mockito

我在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上的交換方法已重載,但由於存根中存在類型,這不應該造成問題。 我在這里俯瞰什么?

對於RestTemplate上的exchange方法,存根定義錯誤。

第三個參數不是RequestEntity而是包含請求的HttpEntity 通過此存根更改,可以找到調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM