一、Struts测试概述
一个具有良好系统架构的J2EE应用程序至少有三层组成,即表现层,商业层和系统集成层(包括数据存取以及和其他系统集成),目前, Struts是应用比较广泛,实现MVC2模式应用于表现层的一种技术. 在这里面,Struts Action主要用来完成一些简单的数据校验,转换,以及流程转发控制(注意:这里流程不是业务规则). 因此在对整个应用程序进行测试时,我们同时也要测试Struts Action.
但是,测试Struts Action相对测试简单的JavaBean是比较困难,因为Struts是运行在Web服务器中, 因此要测试Struts Action就必须发布应用程序然后才能测试. 我们想象一下,对于一个拥有上千个JSP page和数百甚至数千Java Classes的大规模应用程序,要把他们发布到诸如Weblogic之类的应用服务器再测试,需要多少的时间和硬件资源? 所以这种模式的测试是非常费时费力的.
所以,如果有一种办法能够不用发布应用程序,不需要Web服务器就能象测试普通Java Class一样测试Struts Action,那就能极大地加强Struts的可测试性能,使应用程序测试更为容易,简单快速. 现在这个工具来了,这就是StrutsTestCase.
二、StrutsTestCase 概述
StrutsTestCase 是一个功能强大且容易使用的Struts Action开源测试工具,它本身就是在大名鼎鼎的JUnit基础上发展起来的。因此通过和JUnit结合使用能极大加强应用程序的测试并加快应用程序的开发.
StrutsTestCase提供了两者测试方式,模仿方式和容器测试方式. 所谓模仿方式就是有StrutsTestCase本身来模拟Web服务器. 而容器测试方式则需要Web服务器. 本文要讨论的是前者,原因很简单,不需要Web服务器就能象测试普通的Java Class一样测试Struts Action.
三、准备StrutsTestCase和Struts Action/ActionForm/Config
StrutsTestCase是一个开源工具,可以到http://strutstestcase.sourceforge.net下载. 目前最新版本是2.1.3,如果你使用Servlet2.3就下载StrutsTestCase213-2.3.jar,使用Servlet2.4的就下载StrutsTestCase213-2.4.jar.另外StrutsTestCase本身就是从JUnit继承的,所以你还需要下载JUnit3.8.1.
在本文中,我们用一个简单的例子来做测试. 假设我们有一张表Hotline(country varchar2(50),pno varchar2(50)),我们要做的是根据输入条件从这张表检索相应的记录.检索条件是country.
Value Object:
package sample;
public class HotlineDTO implements Serializable{
private String country = "";
private String pno = "";
/**
* Method HotlineActionForm
*
*
*/
public HotlineDTO () {
super();
}
public void setCountry(String country) {
this.country = country;
}
public void setPno(String pno) {
this.pno = pno;
}
public String getCountry() {
return (this.country);
}
public String getPno() {
return (this.pno);
}
}
ActionForm:
package sample;
import org.apache.struts.action.ActionForm;
public class HotlineActionForm extends ActionForm{
private String country = "";
private String pno = "";
/**
* Method HotlineActionForm
*
*
*/
public HotlineActionForm() {
super();
}
public void setCountry(String country) {
this.country = country;
}
public void setPno(String pno) {
this.pno = pno;
}
public String getCountry() {
return (this.country);
}
public String getPno() {
return (this.pno);
}
}
