Listing 10-9.ActivateAccountController
public class ActivateAccountController extends AbstractController {
private AccountService accountService;
public ActivateAccountController() {
setSupportedMethods(new String[]{"POST"});
}
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String idParam = request.getParameter("id");
if (! StringUtils.hasText(idParam)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Missing id parameter");
return null;
}
Long id = null;
try {
id = Long.valueOf(idParam);
} catch(NumberFormatException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"ID must be a number");
return null;
}
accountService.activateAccount(id); // let the infrastructure handle
// the business exception of
// AccountNotFoundException
return new ModelAndView("success"); // this should redirect somewhere
}
}
We introduced a few conditions in this Controllerthat are ripe for testing. First, the id
parameter could be missing or empty. Second, the idparameter could have an incorrect for-
mat. Third, the activateAccount()method itself could throw an exception. Fourth, the client
could attempt to access this Controllerwith a HTTP GET.
That’s a lot to test, but as you’ll see it’s quite easy with the Servlet API stubs in tandem
with mock objects. Let’s first set up the test, including the creation of the Controller, the mock
for the AccountServiceobject, and the stubs. See Listing 10-10.
298 CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS