Java 如何在模拟HTTPResponse中添加头

Java 如何在模拟HTTPResponse中添加头,java,unit-testing,junit,mockito,wiremock,Java,Unit Testing,Junit,Mockito,Wiremock,我想检索response.containsHeader(HttpHeaders.CACHE\u CONTROL),但每次它在我的测试用例执行中返回false。请建议如何添加HttpHeaders.CACHE\u CONTROL作为我的模拟HttpResponse。由于您创建了一个HttpResponse的模拟(不是间谍),这意味着,无论您对该模拟对象调用什么方法,如果它的存根未定义,那么它将返回默认值或null 在您的情况下,由于您尚未定义存根httpResponse.containsHeade

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

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

在您的情况下,由于您尚未定义存根httpResponse.containsHeader(..) 它永远不会进入HttpResponseProxy类的内部实现逻辑,即

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;
}
所以除非你说

public boolean containsHeader(String name) {
    return this.original.containsHeader(name);
  }
它永远不会变成现实

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

线路

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

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

java.net.http.HttpResponse没有containsHeader方法。您在这里指的是哪种响应类型?org.apache.http.HttpResponseIt有效。有没有办法从响应中获取HttpHeaders.CACHE\u控制值?
when(httpEntity.getContentType()).thenReturn(new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()),
            new BasicHeader(HttpHeaders.CACHE_CONTROL, "100"));