Monday, March 10, 2014

Unit Testing Servlets With Spring

I realize that the ideal situation when it comes to unit testing servlets is to separate the business logic from the servlet. The idea being you'll probably use that logic somewhere else and by not depending on the Servlet API your tests should be easier to maintain. But what if - for whatever reason - you really wanted to write a unit test for a servlet. How would you do that?

A lot of the resources I read talked about using Mockito in order to mock the HttpServletRequest and HttpServletResponse interfaces. That seems like a lot of work, though. A much simpler approach would be to use the Spring Framework.

Suppose you had the following Servlet:
package stuff;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {


      PrintWriter printWriter = response.getWriter();
      printWriter.println("<b>Hello World</b>");
Here's how you would test it using Spring:
package stuff;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;


import javax.servlet.ServletException;

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

public class HelloWorldServletTest {

   public void testServletDisplaysHelloWorld() throws IOException, ServletException {
      MockHttpServletRequest request = new MockHttpServletRequest();
      MockHttpServletResponse response = new MockHttpServletResponse();

      HelloWorldServlet servlet = new HelloWorldServlet();
      servlet.doGet(request, response);

      assertThat(response.getContentType(), equalTo("text/html"));
      assertThat(response.getContentAsString(), equalTo("<b>Hello World</b>" + System.getProperty("line.separator")));
See Also: Matf's blog post titled "Writing Unit Tests for Servlets"

No comments:

Post a Comment