- Keep handy JMock Cheat Sheet , especially the Methods and Expectations part
- Use MockHttpServletResponse, MockHttpServletRequest and MockHttpSession in the package org.springframework.mock.web to mock web response, request and session respectively.
- 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");
- Finally use ModelAndView modelAndView = myController.handleRequest(mockRequest, mockResponse);
- 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:
Post a Comment