How to create HttpServletResponse for unit tests in Spring?

With powermock-api-mockito, HttpServletResponse could be mocked and response headers verified.

Java code snippet from the servlet method:

response.setHeader("Cache-Control", "max-age=123456789");
response.setHeader("Content-Type", "video/mp4");
response.setHeader("Content-Disposition", "inline");
response.setHeader("Accept-Ranges","bytes");

Unit Test:

import static org.mockito.Mockito.mock
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

final HttpServletResponse response = mock(HttpServletResponse.class);
final HttpServletRequest request = mock(HttpServletRequest.class);
servlet.doGet();
verify(response).setHeader("Cache-Control", "max-age=123456789");
verify(response).setHeader("Content-Type", "video/mp4");
verify(response).setHeader("Content-Disposition", "inline");
verify(response).setHeader("Accept-Ranges","bytes");

verify(response).setHeader("Content-Length","421854");      
verify(response, times(1)).setHeader("Accept-Ranges","bytes");

For stubbing OutputStream, you could use when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class));

There is more useful information in this answer https://stackoverflow.com/a/24593642/3511379


Using spring-test dependency you could use the class MockHttpServletResponse

This class contains methods to fetch the content of the resulting stream like;

  • byte[] getContentAsByteArray()
  • String getContentAsString()

And also there are methods to inspect the headers.

For mor information about the class you could visit:

  • MockHttpServletResponse JavaDoc Spring 4.2
  • MockHttpServletResponse JavaDoc Spring 5.x

In Spring Test documentation there is some interesting info about Servlet API for testing. Also this documentation recommends to use the Spring test components before others like EasyMock to test Spring classes

These mock objects are targeted at usage with Spring’s Web MVC framework and are generally more convenient to use than dynamic mock objects such as EasyMock or alternative Servlet API mock objects such as MockObjects.

Is preferible to use the EasyMock to test your classes and services without Spring and use the Spring test Runner and spring test framework utilities to test Spring components like Spring MVC, Spring Security,...


Below way by using EasyMock

 HttpServletRequest mockRequest = EasyMock.createMock(HttpServletRequest.class);
 HttpServletResponse mockResponse = EasyMock.createMock(HttpServletResponse.class);

Using spring mock class

import  org.springframework.mock.web.MockHttpServletResponse;
import  org.springframework.mock.web.MockHttpServletRequest;

HttpServletRequest httpServletRequest = new MockHttpServletRequest();
HttpServletResponse httpServletResponse = new MockHttpServletResponse();