Monday, July 14, 2008

Testing a SimpleFormController

Testing a SimpleFormController using JUnit and JMock was a small challenge I came across. After hitting a number of hurdles I managed to write tests that were meaningful and worked. Following points noted for people on similar quest :):

  1. Keep handy JMock Cheat Sheet , especially the Methods and Expectations part
  2. Use MockHttpServletResponse, MockHttpServletRequest and MockHttpSession in the package org.springframework.mock.web to mock web response, request and session respectively.
  3. Remember you can construct post requests and get requests with your MockHttpServletRequest using: MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST","myUrl"); and MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET","myUrl");
  4. Finally use ModelAndView modelAndView = myController.handleRequest(mockRequest, mockResponse);
  5. Use JUnit asserts to verify ModelAndView as per your expectations

Generally your controller will follow this path: receive request-process-return ModelAndView to render. Processing may involve using the command object and passing values to the backend for processing. In your controller tests do NOT attempt to check backend- just mock it. Focus on checking the controller. A combination of expectations and asserts is your best bet to do the testing thoroughly. Let us explore a small example based on these principles in our next post.

No comments: