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

import action.MathAction;
import com.opensymphony.xwork2.ActionProxy;
import org.apache.struts2.StrutsSpringTestCase;

public class TestMathAction  extends StrutsSpringTestCase{
    private MathAction action;
    private ActionProxy proxy;

    protected String getContextLocations() {
        return "spring/applicationContext.xml";
    }

    private void init(){
        proxy=getActionProxy("/add");
        action=(MathAction)proxy.getAction();
    }
    public void testAdd() throws Exception{
        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也是需要的。