如何在模拟 HTTPResponse 中添加 header

How to add header in mock HTTPResponse

public HttpResponse mockHttpResponse(int status, Token token) throws Exception {
    HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(status);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(httpResponse.getEntity()).thenReturn(httpEntity);
    when(httpEntity.getContentType()).thenReturn(new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()),
            new BasicHeader(HttpHeaders.CACHE_CONTROL, "100"));
    ObjectMapper objectMapper = new ObjectMapper();
    byte[] bytes = objectMapper.writeValueAsBytes(token);
    when(httpEntity.getContent()).thenReturn(getInputStream(bytes));
    return httpResponse;
}

我想检索 response.containsHeader(HttpHeaders.CACHE_CONTROL),但每次都返回 false在我的测试用例执行中。请建议我如何添加 HttpHeaders.CACHE_CONTROL 作为我的模拟 HttpResponse。

由于您已经创建了 HttpResponse 的 Mock(不是间谍),这意味着,无论您对该模拟对象调用什么方法,如果它的存根未定义,那么它将 return 默认或 null。

在你的情况下,因为你还没有定义存根 httpResponse.containsHeader(..) 它永远不会进入 HttpResponseProxy class 的内部实现逻辑,即

public boolean containsHeader(String name) {
    return this.original.containsHeader(name);
  }

所以除非你说,

Mockito.when(httpResponse.containsHeader(CACHE_CONTROL)).thenReturn(true);

它永远不会 return 正确。

还有一件事,我想提一下:

when(httpEntity.getContentType()).thenReturn(new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()),
            new BasicHeader(HttpHeaders.CACHE_CONTROL, "100"));

意味着如果httpEntity上的方法'getContentType'被调用两次,那么首先它会return 'Content-Type: application/json; charset=UTF-8' 然后它会return 'Cache-Control: 100'