Info |
---|
The example code for this tutorial, unit_testing, is available for checkout at https://svn.apache.org/repos/asf/struts/sandbox/trunk/struts2examples/ |
Introduction
...
To test the validate method we want Struts to call the Struts action that will cause the Action class's validate and execute methods to be run. In the example application this action is register.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<action name="register" class="org.apache.struts.register.action.Register" method="execute"> <result name="success">/thankyou.jsp</result> <result name="input">/register.jsp</result> </action> |
...
The input fields for the form have the following name values: personBean.firstName, personBean.lastName, personBean.email, and personBean.age. When the user fills out those fields Struts will take the values and provide them to the appropriate set methods of the personBean object. So as part of the test I need to simulate the user filling out these form fields. The StrutsTestCase provides a request object (of type MockHttpServletRequest) that I can use to set these values in the request scope.
Code Block | |||||||
---|---|---|---|---|---|---|---|
| |||||||
@Test public void testExecuteValidationPasses() throws Exception() { request.setParameter("personBean.firstName", "Bruce"); request.setParameter("personBean.lastName", "Phillips"); request.setParameter("personBean.email", "bphillips@ku.edu"); request.setParameter("personBean.age", "19"); ActionProxy actionProxy = getActionProxy("/register.action"); Register action = (Register) actionProxy.getAction() ; assertNotNull("The action is null but should not be.", action); String result - actionProxy.execute(); assertEquals("The execute method did not return " + ActionSupport.SUCCESS + " but should have.", ActionSupport.SUCCESS, result); } |
...
To test that validation should fail, I just need to have a test method that doesn't provide input for a form field. For example, in the validate method of the Register Action class, is a test to ensure the user has entered some information for the personBean.firstName input field. In the test method I would just not use the request object to set a parameter for that field.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
@Test public void testExecuteValidationFailsMissingFirstName() throws Exception() { //request.setParameter("personBean.firstName", "Bruce"); request.setParameter("personBean.lastName", "Phillips"); request.setParameter("personBean.email", "bphillips@ku.edu"); request.setParameter("personBean.age", "19"); ActionProxy actionProxy = getActionProxy("/register.action"); Register action = (Register) actionProxy.getAction() ; assertNotNull("The action is null but should not be.", action); String result - actionProxy.execute(); assertEquals("The execute method did not return " + ActionSupport.INPUT + " but should have.", ActionSupport.INPUT, result); } |
...