【问题标题】:How to add header in mock HTTPResponse如何在模拟 HTTPResponse 中添加标头
【发布时间】:2020-07-02 11:49:46
【问题描述】:
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。

【问题讨论】:

  • java.net.http.HttpResponse 没有方法 containsHeader。您在这里指的是哪种响应类型?
  • org.apache.http.HttpResponse

标签: java unit-testing junit mockito wiremock


【解决方案1】:

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

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

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

所以除非你说,

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

它永远不会返回 true。

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

线

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

表示如果httpEntity上的方法'getContentType'被调用两次,那么首先它会返回'Content-Type: application/json; charset=UTF-8' 那么它将返回 'Cache-Control: 100'

【讨论】:

  • 成功了。有没有办法从响应中获取 HttpHeaders.CACHE_CONTROL 值?
猜你喜欢
  • 2018-05-22
  • 1970-01-01
  • 1970-01-01
  • 2018-05-05
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
相关资源
最近更新 更多