struts2 单元测试

对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

[java] view plain copy
  1. packagemodel;
  2. publicclassAccount{
  3. privateStringuserName;
  4. privateStringpassword;
  5. publicAccount(){
  6. }
  7. publicAccount(StringuserName,Stringpassword){
  8. this.userName=userName;
  9. this.password=password;
  10. }
  11. publicStringgetUserName(){
  12. returnuserName;
  13. }
  14. publicvoidsetUserName(StringuserName){
  15. this.userName=userName;
  16. }
  17. publicStringgetPassword(){
  18. returnpassword;
  19. }
  20. publicvoidsetPassword(Stringpassword){
  21. this.password=password;
  22. }
  23. }

AccountAction.java

[java] view plain copy
  1. packageaction;
  2. importcom.opensymphony.xwork2.ActionSupport;
  3. importmodel.Account;
  4. importjava.util.logging.Logger;
  5. publicclassAccountActionextendsActionSupport{
  6. privateAccountaccountBean;
  7. publicStringexecute()throwsException{
  8. returnSUCCESS;
  9. }
  10. publicvoidvalidate(){
  11. if(accountBean.getUserName().length()==0){
  12. addFieldError("accountBean.userName","Usernameisrequired.");
  13. }
  14. if(accountBean.getUserName().length()<5){
  15. addFieldError("accountBean.userName","Usernamemustbeatleast5characterslong.");
  16. }
  17. if(accountBean.getUserName().length()>10){
  18. addFieldError("accountBean.userName","Usernamecannotbeatmorethant10characterslong.");
  19. }
  20. }
  21. publicAccountgetAccountBean(){
  22. returnaccountBean;
  23. }
  24. publicvoidsetAccountBean(AccountaccountBean){
  25. this.accountBean=accountBean;
  26. }
  27. }

测试类:

TestAccountAction.java

[java] view plain copy
  1. packageut;
  2. importaction.AccountAction;
  3. importcom.opensymphony.xwork2.ActionProxy;
  4. importcom.opensymphony.xwork2.config.ConfigurationProvider;
  5. importorg.apache.struts2.StrutsTestCase;
  6. importstaticorg.testng.AssertJUnit.*;
  7. publicclassTestAccountActionextendsStrutsTestCase{
  8. privateAccountActionaction;
  9. privateActionProxyproxy;
  10. privatevoidinit(){
  11. proxy=getActionProxy("/createaccount");//actionurl,可以写扩展名".action"也可以干脆不写
  12. action=(AccountAction)proxy.getAction();
  13. }
  14. publicvoidtestUserNameErrorMessage()throwsException{
  15. request.setParameter("accountBean.userName","Bruc");
  16. request.setParameter("accountBean.password","test");
  17. init();
  18. proxy.execute();
  19. assertTrue("ProblemTherewerenoerrorspresentinfieldErrorsbutthereshouldhavebeenoneerrorpresent",
  20. action.getFieldErrors().size()==1);
  21. assertTrue("Problemfieldaccount.userNamenotpresentinfieldErrorsbutitshouldhavebeen",
  22. action.getFieldErrors().containsKey("accountBean.userName"));
  23. }
  24. publicvoidtestUserNameCorrect()throwsException{
  25. request.setParameter("accountBean.userName","Bruce");
  26. request.setParameter("accountBean.password","test");
  27. init();
  28. Stringresult=proxy.execute();
  29. assertTrue("ProblemTherewereerrorspresentinfieldErrorsbutthereshouldnothavebeenanyerrorspresent",
  30. action.getFieldErrors().size()==0);
  31. assertEquals("Resultreturnedformexecutingtheactionwasnotsuccessbutitshouldhavebeen.",
  32. "success",result);
  33. }
  34. }

测试逻辑比较简单,action中的validate方法会保证用户名长度在5--9之间。

定义struts.xml,放在类路径的根目录下,而非web-inf/classes下,否则会找不到,不会加载你定义的内容。

[java] view plain copy
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <!DOCTYPEstrutsPUBLIC
  3. "-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <packagename="testit"namespace="/"extends="struts-default">
  7. <actionname="createaccount"class="action.AccountAction">
  8. <resultname="success">/index.jsp</result>
  9. <resultname="input">/createaccount.jsp</result>
  10. </action>
  11. </package>
  12. </struts>

至于action/result的定义中用到的jsp页面,不必真实存在,保持不为空就行,否则,action测试的时候,会说result未定义之类的错误,因为此测试会模拟action真实状态下的运行。运行,一切OK。

正因为会模拟真实状态下的运行,所以拦截器也会正常被触发,下面再定义一个拦截器测试一下:

MyInterceptor.java

[java] view plain copy
  1. packageinterceptor;
  2. importcom.opensymphony.xwork2.ActionInvocation;
  3. importcom.opensymphony.xwork2.interceptor.AbstractInterceptor;
  4. publicclassMyInterceptorextendsAbstractInterceptor{
  5. publicStringintercept(ActionInvocationactionInvocation)throwsException{
  6. System.out.println("beforeprocessing");
  7. Stringrst=actionInvocation.invoke();
  8. System.out.println("byebye"+actionInvocation.getProxy().getMethod());
  9. returnrst;
  10. }
  11. }

修改一下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包如下图:

struts2 单元测试

都是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

[java] view plain copy
  1. packageaction;
  2. importcom.opensymphony.xwork2.ActionContext;
  3. importcom.opensymphony.xwork2.ActionSupport;
  4. importorg.apache.struts2.ServletActionContext;
  5. importservice.MathService;
  6. publicclassMathActionextendsActionSupport{
  7. privateMathServiceservice;
  8. publicStringexecute()throwsException{
  9. ServletActionContext.getRequest().setAttribute("add.result",service.add(1,2));
  10. returnSUCCESS;
  11. }
  12. publicMathServicegetService(){
  13. returnservice;
  14. }
  15. publicvoidsetService(MathServiceservice){
  16. this.service=service;
  17. }
  18. }

MathService.java

[java] view plain copy
  1. packageservice;
  2. publicclassMathService{
  3. publicintadd(inta,intb){
  4. returna+b;
  5. }
  6. }

测试类TestMathAction,测试一下MathService.add是否能正确地返回两个数相加的值。

[java] view plain copy
  1. importaction.MathAction;
  2. importcom.opensymphony.xwork2.ActionProxy;
  3. importorg.apache.struts2.StrutsSpringTestCase;
  4. publicclassTestMathActionextendsStrutsSpringTestCase{
  5. privateMathActionaction;
  6. privateActionProxyproxy;
  7. protectedStringgetContextLocations(){
  8. return"spring/applicationContext.xml";
  9. }
  10. privatevoidinit(){
  11. proxy=getActionProxy("/add");
  12. action=(MathAction)proxy.getAction();
  13. }
  14. publicvoidtestAdd()throwsException{
  15. init();
  16. proxy.execute();
  17. assertEquals(request.getAttribute("add.result"),3);
  18. }
  19. }

这里有一个小trick,默认情况下,applicationContext.xml也要放在classpath的根目录下,但如果项目需要不放在那里,就要覆盖getContextLocations方法返回其class path,开头可以有也可以没有“/”,这里我放在包spring下,所以就返回spring/applicationContext.xml,至于struts和spring整合的配置就不用写了,想必大家都会。需要的jar在上面的基础上,加入struts2-spring-plugin-2.2.1.1.jar就行了,对了,两种测试都需要jsp-api.jarservlet-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

你可能感兴趣的:(struts2)