Pivotal Knowledge Base

Follow

Unit Testing a Dispatcher Servlet with a Custom Context Class

Environment

 Product  Version
 Spring Framework  3.0

Purpose

Unit testing a dispatcher servlet is essential in building a web application.

This article provides information on how to check the functionality of your custom context class and the life cycle of a dispatcher servlet without having to run the entire application.

Resolution

To unit test a dispatcher servlet in Spring Framework 3.0, you must write a Test Class extending TestCase just like any other JUnit Test. Create a MockServletConfig to set your own context class.

The sample provided below allows you to check for a controller inside a custom WebApplicationContext.

Note: Servlet-api-2.5.jar and spring-test 3.0.3 was used in this testing:

public class DispatcherServletTest extends TestCase {

  DispatcherServlet dispatcherServlet;

   protected void setUp() throws Exception{

     dispatcherServlet = new DispatcherServlet();

       MockServletConfig servletConfig = new MockServletConfig(new MockServletContext(), "ServletName");
       dispatcherServlet.setContextClass(MyXmlWebApplicationContext.class);
       dispatcherServlet.init(servletConfig);

} public void testControllerInContext() throws Exception{ MockHttpServletRequest request = new MockHttpServletRequest(dispatcherServlet.getServletContext(), "GET", "/validrequest.do"); MockHttpServletResponse response = new MockHttpServletResponse(); dispatcherServlet.service(request, response); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); dispatcherServlet.destroy();
} }

Comments

Powered by Zendesk