Struts2 Action的单元测试
作者:网络转载 发布时间:[ 2013/9/18 13:34:31 ] 推荐标签:
修改一下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 bye execute
都是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
package action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import service.MathService;
public class MathAction extends ActionSupport{
private MathService service;
public String execute() throws Exception {
ServletActionContext.getRequest().setAttribute("add.result",service.add(1,2));
return SUCCESS;
}
public MathService getService() {
return service;
}
public void setService(MathService service) {
this.service = service;
}
}
MathService.java
package service;
public class MathService {
public int add(int a,int b){
return a+b;
}
}

sales@spasvo.com