StrutsTestCase介绍

StrutsTestCase介绍

1.   概要

StrutsTestCase for JUnitJunit TestCase的扩展,提供基于Struts框架的代码测试装置。StrutsTestCase同时提供Mock 对象方法和Cactus方法用来实际运行Struts ActionServlet,你既可以通过运行servlet引擎来测试,也可以不通过它。因为StrutsTestCase使用ActionServlet控制器来测试你的代码,因此你不仅可以测试Action对象的实现,而且可以测试mappingsfrom beans以及forwards声明。

使用StrutsTestCase不启动servlet容器来测试struts应用程序(容器外测试)也属于Mock对象测试,但是与EasyMock不同的是,EasyMock是提供了创建Mock对象的API,而StrutsTest则是专门负责测试Struts应用程序的Mock对象测试框架。

除了容器外测试,StrutsTest也可以很方便的用容器内的测试。

StrutsTestCase当前的版本是StrutsTest2.1.2,支持Servlet2.22.3的规范,并且支持Struts1.1Cactus1.6.1Junit3.8.1。在这个版本中不支持Struts1.0。如果需要测试struts1.0的应用程序,对应的版本是StrutsTest2.0。可以从http://sourceforge.net/projects/strutstestcase/下载。

2.   使用方法

首先应从StrutsTestCase主页下载该工具,解压后会有一个JAR文件,还有一个例子以及API DOC。编写StrutsTestCase时需将这个JAR文件引入到工程中(和Struts中的JAR文件放在一起),此外由于是对JUnit的扩展,因此还必须将Junit.jar引入到工程中

上面已经介绍过有两种测试方法,下面分别来简单说明:

1)                  MockStrutsTestCaseMock对象测试):通过模拟容器来进行测试。MockStrutsTestCase用一套HttpServlet mock对象在不需要运行Servlet引擎的情况下来模拟容器环境。

2)                  CactusStrutsTestCaseIn-container testing):在真实运行的容器中通过使用Cactus测试框架进行测试。

说明:上述两个类都是对Junit TestCase的扩展。如果要将Mock对象测试方法改为Cactus方法,只需要将我们所定义子类的父类由MockStrutsTestCase改为CactusStrutsTestCase即可,而不需要更改内部代码。

命名规则:对于类的命名没有严格的规范,但个人建议使用Test+要测试的Action名;方法名可以任意取,但注意一点:系统只会自动运行以”test”开头的方法名来进行测试。

下面通过一个我写的一个实例来说明具体使用方法,先来看一个ActionRegisterAction.java)中的代码:

 

package com.firefly;

 

import org.apache.struts.action.*;

import javax.servlet.http.*;

/**

 * @author firefly

 */

public class RegisterAction extends Action{

    public ActionForward execute(ActionMapping mapping,ActionForm form,

     HttpServletRequest req, HttpServletResponse res){

            RegisterForm rf = (RegisterForm)form;

            //String userName = rf.getUserName();

            String password1 = rf.getPassword1();

            String password2 = rf.getPassword2();

            if(password1.equals(password2)){

               try{

                    return mapping.findForward("success");

                }

                catch(Exception e){

                    return mapping.findForward("failure");

                }

            }

            return mapping.findForward("failure");

        }

 

}

功能很简单,即查看两次输入的密码是否相同,相同则转到success,否则转到failure。下面是测试代码(TestRegisterAction.java):

 

package com.firefly;

import servletunit.struts.*;

/**

 * @author firefly

 */

public class TestRegisterAction extends MockStrutsTestCase{

   

    public void setUp() throws Exception{

        super.setUp();

    }

    public void tearDown() throws Exception{

        super.tearDown();

    }

   

    public TestRegisterAction(String testName){

        super(testName);

    }

   

    public void testSuccessfulLogin(){

        setRequestPathInfo("/register");

        addRequestParameter("userName","hellking");

        addRequestParameter("password1","123");

        addRequestParameter("password2","123");

        actionPerform();

        verifyForward("success");

    }

    public void testFailedLogin(){

        setRequestPathInfo("/register");

        addRequestParameter("userName","hellking");

        addRequestParameter("password1","123");

        addRequestParameter("password2","");

        actionPerform();

        verifyForward("failure");

    }

 

}

说明:

1)      如果overridesetUp()tearDown()方法,那么必须在第一行显示调用其父类的相应方法,原因很简单,父类在这两个方法中定义了很多内容来保证程序能够按照既定规则执行,所以我们必须加载它。

2)      在测试方法中,我们需要做的第一件事是通知Struts在这个测试中要使用哪一个映射(mapping),我们指定一个和Struts mapping相关联的路径,这与Struts标签库方法中使用的机制相同。

3)      我们接下来要做的是通过request对象传递form bean属性,这同样与Struts所做的相同。

4)      该到运行action的时候了,我们通过使用actionPerform()方法来完成该任务。

5)      最后要检验的是程序运行结果是否和我们所预期的一样,通过调用verifyForward()方法来进行确认。这里还有可能用到其他一些方法,如:assertEquals()assertNull()verifyNoActionErrors()verifyActionErrors()等等。

6)      即使你在test方法中不进行任何测试,系统也不会提示任何错误(这个与Actionexecute()方法必须返回ActionMapping有所不同),显示的测试结果仍然为成功。你可以在一个test方法中写多个测试,但个人不建议这样使用,这会给方法的命名及程序的结构带来很大的困扰。此外,test方法中遇到测试失败后便会立即返回,而不是继续向下运行(这和and语句颇有相似之处)。

7)      主要函数和作用:

setRequestPathInfo,设置request的请求

addRequestParameter,将参数和对应的值加入request

 actionPerform,执行这个请求

verifyForward,验证forward的名字是否正确

verifyForwardPath,验证forwardpath是否正确

verifyNoActionErrors,验证在action执行过程中没有ActionError产生

verifyActionErrors,验证在action执行过程中产生的ActionError集合的内容

详细请查看API  DOC

引自:--http://tb.blog.csdn.net/TrackBack.aspx?PostId=132722

StrutsTestCase中setContextDirectory的问题

12-21

package configapp.app1;rnimport servletunit.struts.MockStrutsTestCase;rnimport java.io.File;rnrnpublic class TestApp1Action extends MockStrutsTestCasern public TestApp1Action() rn rn public void setUp() throws Exception rn super.setUp(); rn rn public void testSuccessfulLogin() rn setContextDirectory(new File("C:\\Documents and Settings\\YJT1\\jbproject\\configapp\\newweb"));rn this.setServletConfigFile("C:\\Documents and Settings\\YJT1\\jbproject\\configapp\\newweb\\WEB-INF\\web.xml");rn this.addRequestParameter("username1","liuming");rn this.addRequestParameter("password1","wudi");rn setRequestPathInfo("/app1/app1Action");rn actionPerform();rn this.verifyNoActionErrors();rn verifyForward("showresult");rn rn public void testNullInfoLogin() rn setContextDirectory(new File("C:\\Documents and Settings\\YJT1\\jbproject\\configapp\\newweb"));rn this.setServletConfigFile("C:\\Documents and Settings\\YJT1\\jbproject\\configapp\\newweb\\WEB-INF\\web.xml");rn this.addRequestParameter("username1","");rn this.addRequestParameter("password1","");rn setRequestPathInfo("/app1/app1Action");rn actionPerform();rn this.verifyActionErrors(new String[]"error.username.required","error.password.required");rn this.verifyInputForward();rn rnrn这个测试可以执行并且正确,但是如何把相对路径改称绝对路径.在WEB程序运行的时候可以很轻易的通过WEB.xml获得相对路径,但通过ANT整体测试的时候web程序并没有运行,如何获得相对路径?

StrutsTestCase测试Action问题

03-25

以下代码是登录Action中一段,使用StrutsTestCase该如何进行单元测试?rn重点问题是rntusers = udao.findWhereUserIDEquals(userID);rn这里的findWhereUserIDEquals()方法会在数据库中进行查找,测试时不好操作rnrn[b]UserLoginAction.java[/b]rn[code=Java]public ActionForward login(ActionMapping mapping,ActionForm form, HttpServletRequest request,HttpServletResponse response)throws Exceptionrn String userID = WebParamUtils.getParameter(request, "userID", "");rn String password = this.getParameter(request, "userpass", ""); rn TbFilesystemusersDao udao = TbFilesystemusersDaoFactory.create();rn TbFilesystemusers[] tusers = null;rn TbFilesystemusers tuser = null;rn tryrn tusers = udao.findWhereUserIDEquals(userID);rn if(tusers == null || tusers.length == 0)rn request.setAttribute("message", "请您输入正确用户名及密码!");rn return mapping.findForward("logout");rn rn tuser = tusers[0];rn request.setAttribute("userid", username);rn if( !password.equals(tuser.getUserPwd().trim()))rn request.setAttribute("message", "请您输入正确用户名及密码!");rn return mapping.findForward("logout");rn rn Role roles[] = rdao.findWhereRoleCodeEquals(tuser.getUserrole());rn Role role = null;rn if(roles != null && roles.length > 0)rn role = roles[0];rn rn request.getSession().setAttribute(Const.ROLE, role); rn request.getSession().setAttribute(Const.LOGIN_USER, tuser);rn catch(Exception ex)rn ex.printStackTrace();rn request.setAttribute("message", "请您输入正确用户名及密码!");rn return mapping.findForward("logout");rn rn return mapping.findForward("success");rn [/code]rnrn有想法使用MockStrutsTestCase来测试,自己写了个MockUserLoginAction继承上面的UserLoginActionrnrn代码如下:rn[code=Java]rnpublic class MockUserLoginAction extends UserLoginActionrn rn public ActionForward login(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)throws Exceptionrn rn String username = WebParamUtils.getParameter(request, "username", "");rn String password = this.getParameter(request, "userpass", "");rn System.out.println("username");rn System.out.println("password");rn if(username == null || username.length()== 0)rn request.setAttribute("message", "请您输入正确用户名及密码!");rn return mapping.findForward("logout");rn rn if(username!="8000"||password!="123456")rn rn request.setAttribute("message", "请您输入正确用户名及密码!");rn return mapping.findForward("logout");rn rn request.setAttribute("userid", username);rn return mapping.findForward("success");rn rn[/code]rnrnrn测试类代码如下:rn[code=Java]rnpublic void testLoginSuccess() throws Exceptionrnrn STCRequestProcessor.addMockAction("com.zzy.record.action.user.UserLoginAction","com.zzy.record.action.user.MockUserLoginAction");rn setRequestPathInfo("/loginAction");rn addRequestParameter("method","login");rn addRequestParameter("username","8000");rn addRequestParameter("userpass","123456");rn actionPerform();rn //verifyForward("success");rn assertEquals("8000",this.getMockRequest().getAttribute("userid"));rn [/code]rnrnrn但运行出错rn错误信息如下:rnCaused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initialrn at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)rn at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)rn at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)rn at javax.naming.InitialContext.lookup(Unknown Source)rn at com.zzy.record.jdbc.ResourceManager.getConnection(ResourceManager.java:13)rn at com.zzy.record.jdbc.TbFilesystemusersDaoImpl.findByDynamicSelect(TbFilesystemusersDaoImpl.java:1029)rn ... 34 morernrn[b]有没有其它办法可对其进行单元测试?rn万分感谢!!![/b]

StrutsTestCase初学者的烦恼

01-23

今日初学StrutsTestCase。rn配置文件相关部分为:rn rn rn rn rnrn rn rn rnrnaction为:rn public ActionForward execute(rn ActionMapping mapping,rn ActionForm form,rn HttpServletRequest request,rn HttpServletResponse response)rn throws Exception rn RegisterForm registerform = (RegisterForm)form;rn String password1 = registerform.getPassword1();rn System.out.println("password1="+password1);rnrn String password2 = registerform.getPassword2();rn System.out.println("password2="+password2);rnrn if(password1.equals(password2))rnrn tryrnrn return mapping.findForward("success");rnrn rnrn catch(Exception e)rnrn return mapping.findForward("failure");rnrn rnrn rnrn return mapping.findForward("failure");rnrn rnrnform为:rnpublic class RegisterForm extends ActionForm rnrn // --------------------------------------------------------- Instance Variablesrnrn /** password2 property */rn private String password2="123";rnrn /** password1 property */rn private String password1="123";rnrn // --------------------------------------------------------- Methodsrnrn /** rn * Returns the password2.rn * @return Stringrn */rn public String getPassword2() rn return password2;rn rnrn /** rn * Set the password2.rn * @param password2 The password2 to setrn */rn public void setPassword2(String password2) rn this.password2 = password2;rn rnrn /** rn * Returns the password1.rn * @return Stringrn */rn public String getPassword1() rn return password1;rn rnrn /** rn * Set the password1.rn * @param password1 The password1 to setrn */rn public void setPassword1(String password1) rn this.password1 = password1;rn rn rnrnrnrn测试为:rnpublic class TestRegisterAction extends MockStrutsTestCasernrn rnrn public void setUp() throws Exceptionrnrn super.setUp();rnrn rnrn public void tearDown() throws Exceptionrnrn super.tearDown();rnrn rnrn rnrn public TestRegisterAction(String testName)rnrn super(testName);rnrn rnrn rnrn public void testSuccessfulLogin()rnrn setRequestPathInfo("/register");rnrn addRequestParameter("password1","aaa");rn addRequestParameter("password2","aaa");rnrn actionPerform();rnrn verifyForward("success");rnrn rnrnrnrnrnrn结果测试时报错,错误定位在String password1 = registerform.getPassword1();我一跟踪,发现registerform为null,为什么呢?rn应该如何才能顺利使用StrutsTestCase呢?

求助:strutsTestCase无法测试ssh中的struts

08-27

最近应导师要求,学习strutsTestCase来测试struts中的action,可是问题多多。rn我先是创建单独struts项目,测试可以通过。rn再创建struts+hibernate项目,测试也可以通过。rn可是在测试SSH时,却有问题。rn这个是错误:rnjunit.framework.AssertionFailedError: received error 404 : Invalid path was requestedrn at servletunit.HttpServletResponseSimulator.sendError(HttpServletResponseSimulator.java:463)rn at org.apache.struts.action.RequestProcessor.processMapping(RequestProcessor.java:677)rn at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:191)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)rn at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)rn at servletunit.struts.MockStrutsTestCase.actionPerform(MockStrutsTestCase.java:394)rn at com.fang.mytest.TestLoginAction.testSuccessLogin(TestLoginAction.java:31)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rn at java.lang.reflect.Method.invoke(Method.java:597)rn at junit.framework.TestCase.runTest(TestCase.java:168)rn at junit.framework.TestCase.runBare(TestCase.java:134)rn at junit.framework.TestResult$1.protect(TestResult.java:110)rn at junit.framework.TestResult.runProtected(TestResult.java:128)rn at junit.framework.TestResult.run(TestResult.java:113)rn at junit.framework.TestCase.run(TestCase.java:124)rn at junit.framework.TestSuite.runTest(TestSuite.java:232)rn at junit.framework.TestSuite.run(TestSuite.java:227)rn at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:79)rn at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)rn at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)rnrn我的测试类,如下:rnpackage com.fang.mytest;rnrnimport java.io.File;rnrnimport servletunit.struts.MockStrutsTestCase;rnrnpublic class TestLoginAction extends MockStrutsTestCasern public void setUp() throws Exception rn super.setUp();rn String filePath = "E:/Workspaces/sshunittest/WebRoot";rn File web = new File(filePath );rn this.setContextDirectory(web);rn setServletConfigFile(filePath+"/WEB-INF/web.xml");rn// setConfigFile(filePath+"/WEB-INF/web.xml");rn setConfigFile(filePath+"/WEB-INF/struts-config.xml");rn setConfigFile(filePath+"/WEB-INF/applicationContext.xml");rn rnrn public void tearDown() throws Exception rn super.tearDown();rn rnrn public TestLoginAction(String testName) rn super(testName);rn rnrn public void testSuccessLogin() rn setRequestPathInfo("/login");rn addRequestParameter("username","test");rn addRequestParameter("password","123456");rn actionPerform();rn verifyForward("success");rn rnrn public void testFailLogin() rn setRequestPathInfo("/login");rn addRequestParameter("username","smail");rn addRequestParameter("password","123456");rn actionPerform();rn verifyForward("/form/login.jsp");rn rn

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试

关闭