Listing 10-12.testMissingIdParam Method
public void testMissingIdParam() throws Exception {
request.setMethod("POST");
ModelAndView mav = controller.handleRequest(request, response);
assertNull(mav);
assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
assertEquals("Missing id parameter", response.getErrorMessage());
}
Notice that we are using methods provided by the MockHttpServletResponseobject to
manually check the state of the response object. The values that were set in the Controllervia
response.sendError()are then checked with getStatus()and getErrorMessage(). The ability
to introspect the request and response objects is part of the value add the stubs provide, as the
native API interfaces don’t provide this functionality.
For completeness, we’ve included the rest of the tests for the possible error conditions in
the Controller. The last two test cases (Listing 10-13) use both mock objects and stubs to test
the interaction of the Controllerwith the service layer. Fundamentally, it’s no different than
using mocks to replace the DAO layer.
Listing 10-13.Additional Test Cases for ActivateAccountController
public void testBlankIdParam() throws Exception {
request.setMethod("POST");
request.addParameter("id", " ");
ModelAndView mav = controller.handleRequest(request, response);
assertNull(mav);
assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
assertEquals("Missing id parameter", response.getErrorMessage());
}
public void testIdNotANumber() throws Exception {
request.setMethod("POST");
request.addParameter("id", "fwewefas");
ModelAndView mav = controller.handleRequest(request, response);
assertNull(mav);
assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
assertEquals("ID must be a number", response.getErrorMessage());
}
300 CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS