Search code examples
javaspringeasymock

How to create HttpServletResponse for unit tests in Spring?


How to create HttpServletResponse for unit tests, where I can write output stream and headers(not MockHttpServletResponse)? In assert block I expect to compare OutputStream and headers with etalon httpServletResponse.

I used Spring4, java8 and EasyMock lib.


Solution

  • 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:

    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,...

    Example Code:

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();