Listing 10-10.ActivateAccountControllerTest Setup
public class ActivateAccountControllerTest extends MockObjectTestCase {
private ActivateAccountController controller;
private Mock mockAccountService;
private AccountService accountService;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
protected void setUp() throws Exception {
super.setUp();
controller = new ActivateAccountController();
mockAccountService = mock(AccountService.class);
accountService = (AccountService) mockAccountService.proxy();
controller.setAccountService(accountService);
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
Next, let’s create a test for the very simple case of a client attempting to use HTTP
GET instead of HTTP POST. For this test, shown in Listing 10-11, we will configure our
HttpServletRequeststub to report the GET method, and we will call the Controller’s
handleRequest()method. We choose to call this method, even though our controller only
implements handleRequestInternal(), because handleRequest()implements the logic for
checking request methods. We are really testing whether we configured the Controllerto
accept only the POST method, not necessarily the logic that checks the request methods
(since we generally trust the Spring code, but if not, feel free to run the framework’s tests
locally).
Listing 10-11.testGet Method
public void testGetMethod() throws Exception {
request.setMethod("GET");
try {
controller.handleRequest(request, response);
fail("Should have thrown RequestMethodNotSupportedException");
} catch (RequestMethodNotSupportedExceptione) {
// ok
}
}
As you can see, using the stubs is more straightforward than that working with mock
objects. If this test passes, it means that we’ve configured the Controllerto reject GET methods.
For the second test (Listing 10-12), we will use the correct HTTP method, but we will
forget the id parameter. This should not throw any exceptions, but it should set the
HttpServletResponsefor an error state with the correct error message.
CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS 299