很久没有从头搭建Struts2的环境了。最近,认真实践了单元测试Struts2、Spring等Java项目。
今天特意写的是单元测试Struts2的Action,遇到了不少问题,果然是实践出真知啊。
从搭建环境、写代码到写这篇文章,一共花了90分钟。
特别说明:本文是原创,搭建环境、写代码、运行,都是实践并且正确的。
本文是靠谱的,而非简单的复制-粘贴。
1.新建工程,加入相关jar包。
struts.core等struts自己的jar包
spring-core-3.2.0.RELEASE.jar
(用到了里面的一些类,比如看起来挺奇怪的,测试Struts2怎么和Spring扯上关系了。
没有这个包,会报错java.lang.NoClassDefFoundError: org/springframework/core/io/ResourceLoader)
spring-test-3.2.3.RELEASE.jar
Junit的jar包
Tomcat的Server Rumtime lib。
2.新建Action。
public class UserAction {
public String list(){
return "success";
}
}
3.新建单元测试。
package unittest;
import org.apache.struts2.StrutsTestCase;
import org.junit.Test;
import action.UserAction;
import com.opensymphony.xwork2.ActionProxy;
public class ActionUnitTest extends StrutsTestCase {
// 重写父类方法,指定配置文件的名字
protected String[] getContextLocations() {
return new String[] { "struts.xml" };
}
@Test
public void testExecute() throws Exception {
ActionProxy proxy = getActionProxy("/unitTest");
UserAction test = (UserAction) proxy.getAction();
assertNotNull(test);
String result = proxy.execute();
assertEquals("success", result);
}
}
4.Struts配置。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!– Development Mode –>
<constant name="struts.devMode" value="true" />
<package name="manager" namespace="/" extends="struts-default">//不是default
<action name="unitTest" class="action.UserAction" method="list">
<result name="success">unitTest.jsp
</result>
</action>
</package>
</struts>
5.访问web页面测试。
需要在Web.xml中增加
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
访问URL:http://localhost:8080/Struts2UnitDemo/unitTest.action
6.说明
源码优快云下载:http://download.youkuaiyun.com/detail/fansunion/6332115(免积分)
有问题,可以留言,或加入群或者QQ。我抽空答复。