现在的struts2 版比 struts1 测试显的更简单了,我们只需引入struts-junit.jar插件和spring的一些架包即可进行测试.下面的这些架包是必需的(以struts2.1.8.1版为例):
struts2-core-2.1.8.1.jar
xwork-core-2.1.6.jar
freemarker-2.3.15.jar
struts2-junit-plugin-2.1.8.1.jar
commons-logging-1.0.4.jar
commons-fileupload-1.2.1.jar
junit-4.8.2.jar
spring-test-2.5.6.jar
spring-core-2.5.6.jar(如果你还想使用Spring的其他功能,直接引入独立包spring.jar就行了)
以上都是必需的,不过特别要注意的是在不用spring当JavaBean工厂的时候,千万别加入struts2-spring-plugin-2.1.8.1.jar 这个架包,要不然你运行测试程序时它死活不让你通过,就在控制台一直提醒你未配置spring监听.
下面写些例子来说明怎么测试struts2:
被测试的Action:
public class MyAction extends ActionSupport implements ServletResponseAware{
private String name;
private HttpServletResponse response;
@Override
public String execute() throws Exception {
response.setContentType("text/html; charset=utf-8");
response.getWriter().write("Hello world!");
response.getWriter().flush();
return SUCCESS;
}
public String hello() throws Exception {
//...
return "hello";
}
@Override
public void setServletResponse(HttpServletResponse arg0) {
this.response = arg0;
}
//name's getter and setter
}
测试类:
public class MyActionTest extends StrutsTestCase {
//测试Action配置文件是否正确
public void testGetActionMapping() {
ActionMapping mapping = getActionMapping("/test");
assertNotNull(mapping);
assertEquals("/", mapping.getNamespace());
assertEquals("test", mapping.getName());
}
//测试Action代理
public void testGetActionProxy() throws Exception {
//set parameters before calling getActionProxy
request.setParameter("name", "Chase");
ActionProxy proxy = getActionProxy("/test");
assertNotNull(proxy);
MyAction action = (MyAction) proxy.getAction();
assertNotNull(action);
String result = proxy.execute();
assertEquals(ActionSupport.SUCCESS, result);
assertEquals("Chase", action.getName());
}
//测试重写的execute()方法
public void testExecuteAction() throws ServletException, UnsupportedEncodingException {
String output = executeAction("/test");
assertEquals("Hello world!", output);
}
//测试自定义方法
public void testMyMethod() throws Exception {
ActionProxy proxy = getActionProxy("/helloAction");
assertNotNull(proxy);
MyAction action = (MyAction) proxy.getAction();
assertNotNull(action);
String result = proxy.execute();
assertEquals("hello", result);
}
//测试value stack
public void testGetValueFromStack() throws ServletException, UnsupportedEncodingException {
request.setParameter("name", "Chase");
executeAction("/test");
String name = (String) findValueAfterExecute("name");
assertEquals("Chase", name);
}
}
struts.xml部分:
<package name="testPackage" extends="struts-default" namespace="/">
<action name="test" class="com.chase.action.MyAction">
<result>/test-success.jsp</result>
</action>
<action name="*Action" class="com.chase.action.MyAction" method="{1}">
<result name="{1}">/test-success.jsp</result>
</action>
</package>
分享到:
评论