qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

单元测试Struts2的Action(包含源码)

 很久没有从头搭建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

posted on 2013-09-30 11:32 顺其自然EVO 阅读(367) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2013年9月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜