Swadeep Mohanty
Swadeep Mohanty

Reputation: 289

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;
}

I would like to retrieve response.containsHeader(HttpHeaders.CACHE_CONTROL), but every time it is returning false in my test case execution. Please suggest how can I add HttpHeaders.CACHE_CONTROL as my mocked HttpResponse.

Upvotes: 0

Views: 2869

Answers (1)

Abhinaba Chakraborty
Abhinaba Chakraborty

Reputation: 3671

Since you have created a Mock of HttpResponse (not a spy), it means, whatever methods you call on that mocked object, if it's stub is not defined then it will return default or null.

In your case, since you have not defined the stub httpResponse.containsHeader(..) it will never go to the internal implemented logic of HttpResponseProxy class i.e

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

So unless you say,

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

it will never return true.

Another thing, I would like to mention:

The line

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

means that if the method 'getContentType' on httpEntity is called two times, then first it will return 'Content-Type: application/json; charset=UTF-8' then it will return 'Cache-Control: 100'

Upvotes: 1

Related Questions