用StrutsTestCase 测试Struts
1. StrutsTestCase 简介
StrutsTestCase 是标准 Junit TestCase 的一个扩展,为Struts framework提供了方便灵活的测试代码
StrutsTestCase 用 ActionServlet controller 进行测试,我们可测试Action object, mapping, form bean, forwards
StrutsTestCase 提供了 Mock Object 和 Cactus 两种方法来运行Struts ActionServlet,允许在 servlet engine 内或外来测试。
MockStrutsTestCase 使用一系列HttpServlet 模仿对象来模拟容器环境,CactusStrutsTestCase 使用Cactus testing framework在实际的容器
中测试
2. 看StrutsTestCase如何工作
我们用的例子是验证用户名和密码的action,只要接受参数然后进行简单的逻辑验证就行了,所以我们要做的是:
(1)建好目录,准备必要的jar 文件,struts-config.xml, 资源文件
(2)action,formbean 的源文件
(3)test 的源文件
(4)编写ant 文件,进行测试
这里我们用MockStrutsTestCase,CactusStrutsTestCase 的用法也是一样的,只要改一下继承类就行了
先建立目录结构
strutstest
|-- src
|-- war
|-- |-- WEB-INF
|-- |-- |-- classes
|-- |-- |-- lib
把struts 所需要的jarfile 和 strutstest, junit 放入lib
然后写struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<!--
This is the Struts configuration file for the "Hello!" sample application
-->
<struts-config>
<!-- ======== Form Bean Definitions =================================== -->
<form-beans>
<form-bean name="LoginForm" type="LoginForm"/>
</form-beans>
<!-- ======== Global Forwards ====================================== -->
<global-forwards>
<forward name="login" path="/login.jsp"/>
</global-forwards>
<!-- ========== Action Mapping Definitions ============================== -->
<action-mappings>
<!-- Say Hello! -->
<action path = "/login"
type = "LoginAction"
name = "LoginForm"
scope = "request"
validate = "true"
input = "/login.jsp"
>
<forward name="success" path="/hello.jsp" />
</action>
</action-mappings>
<!-- ========== Message Resources Definitions =========================== -->
<message-resources parameter="application"/>
</struts-config>
资源文件我们这里只写一个用于测试的错误信息就行了, application.properties :
error.password.mismatch=password mismatch
写LoginForm 来封状用户名和密码:
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class LoginForm extends ActionForm {
public String username;
public String password;
public void setUsername( String username ) {
this.username = username;
}
public String getUsername(){
return username;
}
public void setPassword( String password ) {
this.password = password;
}
public String getPassword(){
return password;
}
}
下面开始写要测试的action, LoginAction:
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.util.*;
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
String username = ((LoginForm) form).getUsername();
String password = ((LoginForm) form).getPassword();
ActionErrors errors = new ActionErrors();
if ((!username.equals("deryl")) || (!password.equals("radar")))
errors.add("password",new ActionError("error.password.mismatch"));
if (!errors.isEmpty()) {
saveErrors(request,errors);
return new ActionForward(mapping.getInput());
}
HttpSession session = request.getSession();
session.setAttribute("authentication", username);
// Forward control to the specified success URI
return mapping.findForward("success");
}
}
[code]
这里我们接收到包含用户信息的formbean, 首先得到登录信息,然后验证是否有效,如果无效,创建ActionError 信息转到登陆页面,如相符,把验证信息保存到session, 然后转到下个页面。
有这些事情我们可以测试:
(1)LoginForm 工作正常吗?如果在请求中放入合适的参数它会正确的被初始化吗?
(2)如果用户名和密码不匹配,是否适当的错误信息被保存?是否会转到登陆页面?
(3)如果我们提供正确的登陆信息,可以得到正确的页面吗?可以确定不会报错吗?验证信息被保存到session了吗?
StrutsTestCase 赋予你测试所有情况的能力,自动为你启动ActionServlet
先来写一个空的test case, 他和 junit 非常相似
[code]
public class TestLoginAction extends MockStrutsTestCase {
public void setUp() { super.setUp(); } // 如果要重写 setUp(), 则必须显式调用super.setUp()
public void tearDown() { super.tearDown(); }
public TestLoginAction(String testName) { super(testName); }
public void testSuccessfulLogin() {}
}
下面正式写这个测试,向testSuccessfulLogin中添加:
(1)指定一个和struts mapping 相关联的路径,需要说明的是,ActionServlet 默认的搜索WEB-INF下的struts-config.xml, 如果struts-config.xml放在了别的目录下,就要在此之前调用setConfigFile()
setRequestPathInfo("/login");[code]
(2)通过request 对象向 formbean 传递参数
[code]
addRequestParameter("username","deryl");
addRequestParameter("password","radar");
(3)让 Action 执行
actionPerform();
该方法将模拟从浏览器端访问 servlet 容器内的 LoginAction 的过程,先把请求转发给 ActionServlet,ActionServlet再把表单数据组装到LoginForm中,把请求转发给LoginAction
(4)验证转到了正确的页面
verifyForward("success");
(5)确认验证信息被保存到了session
assertEquals("deryl",(String) getSession().getAttribute("authentication"));
(6)确认没有错误信息
verifyNoActionErrors();
现在TestLoginAction 是这样:
import servletunit.struts.*;
public class TestLoginAction extends MockStrutsTestCase {
public TestLoginAction( String testName ){ super( testName ); }
public void testSuccessfulLogin() {
setRequestPathInfo( "/login" );
addRequestParameter( "username", "deryl" );
addRequestParameter( "password", "radar" );
actionPerform();
verifyForward( "success" );
assertEquals("deryl",(String) getSession().getAttribute("authentication"));
verifyNoActionErrors();
}
}
写ant,编译运行一下看看测试结果
为了让 ant 支持 junit 任务,应把 junit.jar 复制到<ANT_HOME>的lib 下
<project name="strutstest" default="test" basedir=".">
<property name="src.home" value="${basedir}/src"/>
<property name="classes.home" value="${basedir}/war/WEB-INF/classes"/>
<property name="lib.home" value="${basedir}/war/WEB-INF/lib"/>
<target name="compile">
<javac srcdir="${src.home}" destdir="${classes.home}" debug="on">
<classpath>
<fileset dir="${lib.home}">
<include name="*.jar"/>
</fileset>
</classpath>
</javac>
</target>
<target name="test" depends="compile">
<junit printsummary="yes">
<classpath>
<pathelement location="${classes.home}"/>
<fileset dir="${lib.home}">
<include name="*.jar"/>
</fileset>
</classpath>
<formatter type="plain"/>
<test name="TestLoginAction"/>
</junit>
</target>
</project>
运行后可以看到一切正常,而且在项目的根目录下自动生成 TEST-TestLoginAction.txt,里面写着测试结果,如测试有问题,就可在这查看错误信息
正常的情况已经测试通过了,现在来看看错误的情况,写一个testFailedLogin :
public void testFailedLogin() {
//setConfigFile("struts-config.xml");
addRequestParameter( "username", "deryl" );
addRequestParameter( "password", "deryl" );
setRequestPathInfo( "/login" );
actionPerform();
verifyForward( "login" );
verifyActionErrors( new String[]{"error.password.mismatch"} );
}
StrutsTestsCase 的简单使用我们已经看过了,和junit 基本相同,很简单
StrutsTestCase 是标准 Junit TestCase 的一个扩展,为Struts framework提供了方便灵活的测试代码
StrutsTestCase 用 ActionServlet controller 进行测试,我们可测试Action object, mapping, form bean, forwards
StrutsTestCase 提供了 Mock Object 和 Cactus 两种方法来运行Struts ActionServlet,允许在 servlet engine 内或外来测试。
MockStrutsTestCase 使用一系列HttpServlet 模仿对象来模拟容器环境,CactusStrutsTestCase 使用Cactus testing framework在实际的容器
中测试
2. 看StrutsTestCase如何工作
我们用的例子是验证用户名和密码的action,只要接受参数然后进行简单的逻辑验证就行了,所以我们要做的是:
(1)建好目录,准备必要的jar 文件,struts-config.xml, 资源文件
(2)action,formbean 的源文件
(3)test 的源文件
(4)编写ant 文件,进行测试
这里我们用MockStrutsTestCase,CactusStrutsTestCase 的用法也是一样的,只要改一下继承类就行了
先建立目录结构
strutstest
|-- src
|-- war
|-- |-- WEB-INF
|-- |-- |-- classes
|-- |-- |-- lib
把struts 所需要的jarfile 和 strutstest, junit 放入lib
然后写struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<!--
This is the Struts configuration file for the "Hello!" sample application
-->
<struts-config>
<!-- ======== Form Bean Definitions =================================== -->
<form-beans>
<form-bean name="LoginForm" type="LoginForm"/>
</form-beans>
<!-- ======== Global Forwards ====================================== -->
<global-forwards>
<forward name="login" path="/login.jsp"/>
</global-forwards>
<!-- ========== Action Mapping Definitions ============================== -->
<action-mappings>
<!-- Say Hello! -->
<action path = "/login"
type = "LoginAction"
name = "LoginForm"
scope = "request"
validate = "true"
input = "/login.jsp"
>
<forward name="success" path="/hello.jsp" />
</action>
</action-mappings>
<!-- ========== Message Resources Definitions =========================== -->
<message-resources parameter="application"/>
</struts-config>
资源文件我们这里只写一个用于测试的错误信息就行了, application.properties :
error.password.mismatch=password mismatch
写LoginForm 来封状用户名和密码:
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class LoginForm extends ActionForm {
public String username;
public String password;
public void setUsername( String username ) {
this.username = username;
}
public String getUsername(){
return username;
}
public void setPassword( String password ) {
this.password = password;
}
public String getPassword(){
return password;
}
}
下面开始写要测试的action, LoginAction:
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.util.*;
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
String username = ((LoginForm) form).getUsername();
String password = ((LoginForm) form).getPassword();
ActionErrors errors = new ActionErrors();
if ((!username.equals("deryl")) || (!password.equals("radar")))
errors.add("password",new ActionError("error.password.mismatch"));
if (!errors.isEmpty()) {
saveErrors(request,errors);
return new ActionForward(mapping.getInput());
}
HttpSession session = request.getSession();
session.setAttribute("authentication", username);
// Forward control to the specified success URI
return mapping.findForward("success");
}
}
[code]
这里我们接收到包含用户信息的formbean, 首先得到登录信息,然后验证是否有效,如果无效,创建ActionError 信息转到登陆页面,如相符,把验证信息保存到session, 然后转到下个页面。
有这些事情我们可以测试:
(1)LoginForm 工作正常吗?如果在请求中放入合适的参数它会正确的被初始化吗?
(2)如果用户名和密码不匹配,是否适当的错误信息被保存?是否会转到登陆页面?
(3)如果我们提供正确的登陆信息,可以得到正确的页面吗?可以确定不会报错吗?验证信息被保存到session了吗?
StrutsTestCase 赋予你测试所有情况的能力,自动为你启动ActionServlet
先来写一个空的test case, 他和 junit 非常相似
[code]
public class TestLoginAction extends MockStrutsTestCase {
public void setUp() { super.setUp(); } // 如果要重写 setUp(), 则必须显式调用super.setUp()
public void tearDown() { super.tearDown(); }
public TestLoginAction(String testName) { super(testName); }
public void testSuccessfulLogin() {}
}
下面正式写这个测试,向testSuccessfulLogin中添加:
(1)指定一个和struts mapping 相关联的路径,需要说明的是,ActionServlet 默认的搜索WEB-INF下的struts-config.xml, 如果struts-config.xml放在了别的目录下,就要在此之前调用setConfigFile()
setRequestPathInfo("/login");[code]
(2)通过request 对象向 formbean 传递参数
[code]
addRequestParameter("username","deryl");
addRequestParameter("password","radar");
(3)让 Action 执行
actionPerform();
该方法将模拟从浏览器端访问 servlet 容器内的 LoginAction 的过程,先把请求转发给 ActionServlet,ActionServlet再把表单数据组装到LoginForm中,把请求转发给LoginAction
(4)验证转到了正确的页面
verifyForward("success");
(5)确认验证信息被保存到了session
assertEquals("deryl",(String) getSession().getAttribute("authentication"));
(6)确认没有错误信息
verifyNoActionErrors();
现在TestLoginAction 是这样:
import servletunit.struts.*;
public class TestLoginAction extends MockStrutsTestCase {
public TestLoginAction( String testName ){ super( testName ); }
public void testSuccessfulLogin() {
setRequestPathInfo( "/login" );
addRequestParameter( "username", "deryl" );
addRequestParameter( "password", "radar" );
actionPerform();
verifyForward( "success" );
assertEquals("deryl",(String) getSession().getAttribute("authentication"));
verifyNoActionErrors();
}
}
写ant,编译运行一下看看测试结果
为了让 ant 支持 junit 任务,应把 junit.jar 复制到<ANT_HOME>的lib 下
<project name="strutstest" default="test" basedir=".">
<property name="src.home" value="${basedir}/src"/>
<property name="classes.home" value="${basedir}/war/WEB-INF/classes"/>
<property name="lib.home" value="${basedir}/war/WEB-INF/lib"/>
<target name="compile">
<javac srcdir="${src.home}" destdir="${classes.home}" debug="on">
<classpath>
<fileset dir="${lib.home}">
<include name="*.jar"/>
</fileset>
</classpath>
</javac>
</target>
<target name="test" depends="compile">
<junit printsummary="yes">
<classpath>
<pathelement location="${classes.home}"/>
<fileset dir="${lib.home}">
<include name="*.jar"/>
</fileset>
</classpath>
<formatter type="plain"/>
<test name="TestLoginAction"/>
</junit>
</target>
</project>
运行后可以看到一切正常,而且在项目的根目录下自动生成 TEST-TestLoginAction.txt,里面写着测试结果,如测试有问题,就可在这查看错误信息
正常的情况已经测试通过了,现在来看看错误的情况,写一个testFailedLogin :
public void testFailedLogin() {
//setConfigFile("struts-config.xml");
addRequestParameter( "username", "deryl" );
addRequestParameter( "password", "deryl" );
setRequestPathInfo( "/login" );
actionPerform();
verifyForward( "login" );
verifyActionErrors( new String[]{"error.password.mismatch"} );
}
StrutsTestsCase 的简单使用我们已经看过了,和junit 基本相同,很简单
irini
2006-01-15 17:48:02
评论:0
阅读:522
引用:0
