public void testOK() throws Exception {
request.setMethod("POST");
request.addParameter("id", "1");
mockAccountService.expects(once())
.method("activateAccount")
.with(eq(new Long(1)));
ModelAndView mav = controller.handleRequest(request, response);
assertNotNull(mav);
assertEquals("success", mav.getViewName());
}
public void testMissingAccountPropogatesException() throws Exception {
request.setMethod("POST");
request.addParameter("id", "1");
mockAccountService.expects(once())
.method("activateAccount")
.with(eq(new Long(1)))
.will(throwException(new AccountNotFoundException(1L)));
try {
controller.handleRequest(request, response);
fail("Should have propogated the AccountNotFoundException");
} catch (AccountNotFoundException e) {
// ok
}
}
Testing Controllers Summary
Testing Controllers is a natural component of a full suite of unit tests for your system.
Controllers written for Spring MVC are easily testable because their dependencies are set
via Dependency Injection, and in general they do not require any facilities from a running
container. The framework code is easily stubbed or mocked so that tests can be written and
verified quickly.
The Spring Framework provides a rich set of testing stubs inside spring-mock.jar, includ-
ing classes to make writing unit tests for web components very simple. These Servlet API stubs
are not specific to Spring, so you may find them useful for any tests you create for your web
components.
When testing components such as Controllers, you should create mock objects for
dependent objects such as the service layer.
Above all, testing web components should not be any different than testing your domain
object model. A combination of stubs and mocks can make writing and running unit tests for
Controllers simple, effective, and productive.
CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS 301