对Struts2进行单元测试,以struts 2.2.1.1为例 ,可以使用struts2发行包中的struts2-junit-plugin-2.2.1.1.jar,它里面提供了两个类StrutsTestCase、StrutsSpringTestCase,分别提供对纯struts应用和struts+spring整合时的单元测试支持。下面分别说明。
1.StrutsTestCase
首先准备一个纯struts2工程,建立工程过程略,但有如下的类:
Account.java,是bean
- packagemodel;
-
- publicclassAccount{
- privateStringuserName;
- privateStringpassword;
-
- publicAccount(){
- }
-
- publicAccount(StringuserName,Stringpassword){
- this.userName=userName;
- this.password=password;
- }
-
- publicStringgetUserName(){
- returnuserName;
- }
-
- publicvoidsetUserName(StringuserName){
- this.userName=userName;
- }
-
- publicStringgetPassword(){
- returnpassword;
- }
-
- publicvoidsetPassword(Stringpassword){
- this.password=password;
- }
- }
AccountAction.java
- packageaction;
-
- importcom.opensymphony.xwork2.ActionSupport;
- importmodel.Account;
-
- importjava.util.logging.Logger;
-
- publicclassAccountActionextendsActionSupport{
-
- privateAccountaccountBean;
- publicStringexecute()throwsException{
- returnSUCCESS;
- }
-
- publicvoidvalidate(){
- if(accountBean.getUserName().length()==0){
- addFieldError("accountBean.userName","Usernameisrequired.");
- }
-
- if(accountBean.getUserName().length()<5){
- addFieldError("accountBean.userName","Usernamemustbeatleast5characterslong.");
- }
-
- if(accountBean.getUserName().length()>10){
- addFieldError("accountBean.userName","Usernamecannotbeatmorethant10characterslong.");
- }
- }
-
- publicAccountgetAccountBean(){
- returnaccountBean;
- }
-
- publicvoidsetAccountBean(AccountaccountBean){
- this.accountBean=accountBean;
- }
- }
测试类:
TestAccountAction.java
- packageut;
-
- importaction.AccountAction;
- importcom.opensymphony.xwork2.ActionProxy;
- importcom.opensymphony.xwork2.config.ConfigurationProvider;
- importorg.apache.struts2.StrutsTestCase;
-
- importstaticorg.testng.AssertJUnit.*;
-
-
- publicclassTestAccountActionextendsStrutsTestCase{
- privateAccountActionaction;
- privateActionProxyproxy;
-
- privatevoidinit(){
- proxy=getActionProxy("/createaccount");
- action=(AccountAction)proxy.getAction();
- }
-
- publicvoidtestUserNameErrorMessage()throwsException{
- request.setParameter("accountBean.userName","Bruc");
- request.setParameter("accountBean.password","test");
-
- init();
- proxy.execute();
-
- assertTrue("ProblemTherewerenoerrorspresentinfieldErrorsbutthereshouldhavebeenoneerrorpresent",
- action.getFieldErrors().size()==1);
- assertTrue("Problemfieldaccount.userNamenotpresentinfieldErrorsbutitshouldhavebeen",
- action.getFieldErrors().containsKey("accountBean.userName"));
- }
-
- publicvoidtestUserNameCorrect()throwsException{
- request.setParameter("accountBean.userName","Bruce");
- request.setParameter("accountBean.password","test");
-
- init();
- Stringresult=proxy.execute();
-
- assertTrue("ProblemTherewereerrorspresentinfieldErrorsbutthereshouldnothavebeenanyerrorspresent",
- action.getFieldErrors().size()==0);
-
- assertEquals("Resultreturnedformexecutingtheactionwasnotsuccessbutitshouldhavebeen.",
- "success",result);
-
- }
- }
测试逻辑比较简单,action中的validate方法会保证用户名长度在5--9之间。
定义struts.xml,放在类路径的根目录下,而非web-inf/classes下,否则会找不到,不会加载你定义的内容。
- <?xmlversion="1.0"encoding="UTF-8"?>
-
- <!DOCTYPEstrutsPUBLIC
- "-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <packagename="testit"namespace="/"extends="struts-default">
- <actionname="createaccount"class="action.AccountAction">
- <resultname="success">/index.jsp</result>
- <resultname="input">/createaccount.jsp</result>
- </action>
- </package>
- </struts>
至于action/result的定义中用到的jsp页面,不必真实存在,保持不为空就行,否则,action测试的时候,会说result未定义之类的错误,因为此测试会模拟action真实状态下的运行。运行,一切OK。
正因为会模拟真实状态下的运行,所以拦截器也会正常被触发,下面再定义一个拦截器测试一下:
MyInterceptor.java
- packageinterceptor;
-
- importcom.opensymphony.xwork2.ActionInvocation;
- importcom.opensymphony.xwork2.interceptor.AbstractInterceptor;
-
- publicclassMyInterceptorextendsAbstractInterceptor{
-
- publicStringintercept(ActionInvocationactionInvocation)throwsException{
- System.out.println("beforeprocessing");
- Stringrst=actionInvocation.invoke();
- System.out.println("byebye"+actionInvocation.getProxy().getMethod());
- returnrst;
- }
- }
修改一下struts.xml,加入拦截器的定义:
<package name="testit" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="testInterceptor" class="interceptor.MyInterceptor"/>
</interceptors>
<action name="createaccount" class="action.AccountAction">
<result name="success">/index.jsp</result>
<result name="input">/createaccount.jsp</result>
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="testInterceptor"/>
</action>
</package>
运行,控制台会输出:
before processing
bye byeexecute
使用的jar包如下图:
都是struts发行包提供的,其它不相关的jar不要加,尤其是以plugin.jar结尾的文件,更不要加struts2-spring-plugin-2.2.1.1.jar,加了会加载相关的东西,但这里却提供不了,导致测试无法运行。实际spring-beans-2.5.6.jar和spring-context-2.5.6.jar也不是必须的,但加了也无所谓,在StrutsSpringTestCase是需要的。另外,web.xml不需要配置,根本不会去这里找配置信息。
2.StrutsSpringTestCase
这个和前面的过程类似,需要的类分别如下。
MathAction.java
- packageaction;
-
- importcom.opensymphony.xwork2.ActionContext;
- importcom.opensymphony.xwork2.ActionSupport;
- importorg.apache.struts2.ServletActionContext;
- importservice.MathService;
-
- publicclassMathActionextendsActionSupport{
- privateMathServiceservice;
-
- publicStringexecute()throwsException{
- ServletActionContext.getRequest().setAttribute("add.result",service.add(1,2));
- returnSUCCESS;
- }
-
- publicMathServicegetService(){
- returnservice;
- }
-
- publicvoidsetService(MathServiceservice){
- this.service=service;
- }
- }
MathService.java
- packageservice;
-
- publicclassMathService{
- publicintadd(inta,intb){
- returna+b;
- }
- }
测试类TestMathAction,测试一下MathService.add是否能正确地返回两个数相加的值。
- importaction.MathAction;
- importcom.opensymphony.xwork2.ActionProxy;
- importorg.apache.struts2.StrutsSpringTestCase;
-
- publicclassTestMathActionextendsStrutsSpringTestCase{
- privateMathActionaction;
- privateActionProxyproxy;
-
- protectedStringgetContextLocations(){
- return"spring/applicationContext.xml";
- }
-
- privatevoidinit(){
- proxy=getActionProxy("/add");
- action=(MathAction)proxy.getAction();
- }
- publicvoidtestAdd()throwsException{
- init();
- proxy.execute();
- assertEquals(request.getAttribute("add.result"),3);
- }
- }
这里有一个小trick,默认情况下,applicationContext.xml也要放在classpath的根目录下,但如果项目需要不放在那里,就要覆盖getContextLocations方法返回其class path,开头可以有也可以没有“/”,这里我放在包spring下,所以就返回spring/applicationContext.xml,至于struts和spring整合的配置就不用写了,想必大家都会。需要的jar在上面的基础上,加入struts2-spring-plugin-2.2.1.1.jar就行了,对了,两种测试都需要jsp-api.jar和servlet-api.jar,去tomcat里copy一份即可,junit.jar也是需要的(废话?!)
参考:https://cwiki.apache.org/WW/struts-2-junit-plugin-tutorial.html
转载自:http://blog.csdn.net/theoffspring/article/details/6314196