Unit Testing Servlets with Mockito

A quick example how to write unit tests for servlets

Okay, I’m writing a Servlet. So I want to write a unit test too.
With Mockito this is a quite simple task.

Here I show you a simple unit test for a Hello World Servlet.
The Servlet returns only „Hello World“.

public class HelloWorldServletTest {

  @Spy private HelloWorldServlet servlet; 
  @Mock private ServletConfig servletConfig;
  @Mock private HttpServletRequest request;
  @Mock private HttpServletResponse response;
  @Mock private ServletOutputStream outputStream;

  @Before public void setUp() {
    MockitoAnnotations.initMocks(this); 
  }

  @Test public void test() throws Exception { 
    when(servlet.getServletConfig()).thenReturn(servletConfig); 
    when(response.getOutputStream()).thenReturn(outputStream);
    servlet.doGet(request, response);
    verify(outputStream).println("Hello World!"); 
  }

}

Mockito offers various annotations. For partial mocking you can use @Spy.
I’m mocking the request and response object with @Mock.
Then I call the servlet.doGet() method. And of course,
I also have to mock ServletConfig and Outputstream too. That’s it.

Pretty easy, isn’t it? Quick note: If your programmic logic is too complex,
move the logic to an concrete class and write a simple unit test.

GitHub-Mark-32px Check out the whole example on Github.

 

Resources

http://site.mockito.org/