Writing Unit Tests for Servlets

When writing unit tests for simple servlets you’ll need to write a lot boilerplate code for mocking out all these HttpServletRequest/Response/Context/… objects every time, plus it feels like too much of a white box test really. Surely there’s a better solution out there already for such a common task?

Included in the list of choices are amongst others:

I decided to use the Spring approach since it meant not introducing any further dependencies into the project, and served my purposes.

private MyServlet servlet;
private MyService myService;

public void setUp() throws Exception {
    // Mock all objects your servlet requires
    myService = createStrictMock(MyService.class);

    // Use a ResourceLoader that loads resources relative to the 'war' directory
    // in the test - in case your servlet loads any resources from the war
    FileSystemResourceLoader warResourceLoader = new FileSystemResourceLoader() {
        public Resource getResource(String location) {
	    return super.getResource("war/" + location);

    // Create mock objects for servlet context & config
    MockServletContext context = new MockServletContext(warResourceLoader);
    MockServletConfig config = new MockServletConfig(context);

    // Create servlet
    servlet = new MyServlet();

Now, in the test, you call your servlet’s method and assert that the response is as expected:

public void testDoGetHttpServletRequestHttpServletResponse() throws Exception {
    // Mock script

    // Create mocks for request/response
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("myparam", "myvalue");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.doGet(request, response);

    // Assert response properties
    assertEquals("application/vnd.ms-excel", response.getContentType());

    // Verify if the servlet response is as expected
    // In this example, Apache POI is used to generate an Excel sheet in the servlet which is checked here
    byte[] responseContent = response.getContentAsByteArray();
    HSSFWorkbook workbook = new HSSFWorkbook(
        new ByteArrayInputStream(responseContent));
    // ...

    // Verify mock script
This entry was posted in Google Web Toolkit, Java, Spring and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s