对Struts2进行单元测试,以struts 2.2.1.1为例 ,可以使用struts2发行包中的struts2-junit-plugin-2.2.1.1.jar,它里面提供了两个类StrutsTestCase、StrutsSpringTestCase,分别提供对纯struts应用和struts+spring整合时的单元测试支持。下面分别说明。
1.StrutsTestCase
- package model;
- public class Account {
- private String userName;
- private String password;
- public Account() {
- }
- public Account(String userName, String password) {
- this.userName = userName;
- this.password = password;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
AccountAction.java
- package action;
- import com.opensymphony.xwork2.ActionSupport;
- import model.Account;
- import java.util.logging.Logger;
- public class AccountAction extends ActionSupport{
- private Account accountBean;
- public String execute() throws Exception {
- return SUCCESS;
- }
- public void validate(){
- if (accountBean.getUserName().length()==0){
- addFieldError("accountBean.userName","User name is required.");
- }
- if (accountBean.getUserName().length()<5){
- addFieldError("accountBean.userName","User name must be at least 5 characters long.");
- }
- if (accountBean.getUserName().length()>10){
- addFieldError("accountBean.userName","User name cannot be at more thant 10 characters long.");
- }
- }
- public Account getAccountBean() {
- return accountBean;
- }
- public void setAccountBean(Account accountBean) {
- this.accountBean = accountBean;
- }
- }
测试类:
TestAccountAction.java
- package ut;
- import action.AccountAction;
- import com.opensymphony.xwork2.ActionProxy;
- import com.opensymphony.xwork2.config.ConfigurationProvider;
- import org.apache.struts2.StrutsTestCase;
- import static org.testng.AssertJUnit.*;
- public class TestAccountAction extends StrutsTestCase {
- private AccountAction action;
- private ActionProxy proxy;
- private void init() {
- proxy = getActionProxy("/createaccount"); //action url,可以写扩展名".action"也可以干脆不写
- action = (AccountAction) proxy.getAction();
- }
- public void testUserNameErrorMessage() throws Exception {
- request.setParameter("accountBean.userName", "Bruc");
- request.setParameter("accountBean.password", "test");
- init();
- proxy.execute();
- assertTrue("Problem There were no errors present in fieldErrors but there should have been one error present",
- action.getFieldErrors().size() == 1);
- assertTrue("Problem field account.userName not present in fieldErrors but it should have been",
- action.getFieldErrors().containsKey("accountBean.userName"));
- }
- public void testUserNameCorrect() throws Exception{
- request.setParameter("accountBean.userName", "Bruce");
- request.setParameter("accountBean.password", "test");
- init();
- String result=proxy.execute();
- assertTrue("Problem There were errors present in fieldErrors but there should not have been any errors present",
- action.getFieldErrors().size()==0);
- assertEquals("Result returned form executing the action was not success but it should have been.",
- "success", result);
- }
- }
测试逻辑比较简单,action中的validate方法会保证用户名长度在5--9之间。
定义struts.xml,放在类路径的根目录下,而非web-inf/classes下,否则会找不到,不会加载你定义的内容。
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <package name="testit" namespace="/" extends="struts-default">
- <action name="createaccount" class="action.AccountAction">
- <result name="success">/index.jsp</result>
- <result name="input">/createaccount.jsp</result>
- </action>
- </package>
- </struts>
至于action/result的定义中用到的jsp页面,不必真实存在,保持不为空就行,否则,action测试的时候,会说result未定义之类的错误,因为此测试会模拟action真实状态下的运行。运行,一切OK。
正因为会模拟真实状态下的运行,所以拦截器也会正常被触发,下面再定义一个拦截器测试一下:
MyInterceptor.java
- package interceptor;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
- public class MyInterceptor extends AbstractInterceptor{
- public String intercept(ActionInvocation actionInvocation) throws Exception {
- System.out.println("before processing");
- String rst= actionInvocation.invoke();
- System.out.println("bye bye "+actionInvocation.getProxy().getMethod());
- return rst;
- }
- }
修改一下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
使用的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 见http://blog.csdn.net/jazywoo123/article/details/8267208
package bijian.test;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.StrutsSpringTestCase;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import bijian.controller.action.UserAction;
public class ActionTestBase extends StrutsSpringTestCase {
/*这个函数相当@Before注解的函数,是调用单元测试后的时候,
首先会执行的方法。可以在这里面做一些必要的准备工作*/
@Override
protected void setUp() throws Exception {
super.setUp();
SessionFactory sessionFactory = lookupSessionFactory(this.request);
Session hibernateSession= getSession(sessionFactory);
TransactionSynchronizationManager.bindResource(sessionFactory,new SessionHolder(hibernateSession));
}
@Override
public String getContextLocations() {
//返回你项目中spring配置文件所在的目录
return "/spring.xml";
}
private Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
FlushMode flushMode = FlushMode.NEVER;
if (flushMode != null) {
session.setFlushMode(flushMode);
}
return session;
}
private SessionFactory lookupSessionFactory(HttpServletRequest request) {
//“sessionFactory”是你spring配置文件(通常是application.xml)中的SessionFactory。
//如:org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
return (SessionFactory)this.applicationContext.getBean("sessionFactory");
}
}
package bijian.test;
public class UserActionTest extends ActionTestBase {
/*这个是单元测试的方法,一个方法测试一个功能,或者一个action*/
public void test_login() throws Exception {
/*request是类StrutsSpringTestCase的成员变量, 是MockHttpServletRequest对象,在这里mock出来的一个web中的request*/
this.request.setParameter("user.username", "jazywoo");
this.request.setParameter("user.password", "123456");
/*我的环境中,返回值是json格式,result将是json格式的一个字符串输入action的地址*/
String result = executeAction("/user/UserAction_login.action");
}
}
package bijian.test;
public class TestMain {
public static void main(String[] args) throws Exception{
UserActionTest userActionTest=new UserActionTest();
userActionTest.setUp();
userActionTest.test_login();
}
}