测试类:

  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;
    }
}