Struts2 Junit测试

简介

Struts2 的Junit测试,可以加快开发调试速度,不用每次更改Action后都重新编译部署等。

优点
编写、返回快速,调试方便。特别是对返回JSON的Action更是方便
缺点
只能获取到Action返回的数据,看不到页面效果

实现

1. 导入 struts2-junit-plugin 插件
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-junit-plugin</artifactId>
    <version>${struts2.version}</version>
    <scope>test</scope>
</dependency>
2. 编写测试类

基础基类有4个,如果有Spring集成,一般使用StrutsSpringTestCase类
通过重写getContextLocations类来重新设置Spring XML加载路径

基类描述
StrutsJUnit4TestCase
StrutsSpringTestCase使用Spring管理依赖
StrutsSpringJUnit4TestCase
StrutsTestCase

实例

实例描述了一个通过Action Uri查找对应Action,执行后检测其执行结果的例子。

public class ExampleActionTest extends StrutsSpringTestCase {// StrutsTestCase
    public static final Log logout = LogFactory.getLog(ExampleActionTest.class);

    @Test
    public void testListExample() throws Exception {
         try {
             //设置 请求参数
             request.setParameter("accountBean.userName", "Bruc");
             request.setParameter("accountBean.password", "test");

             //获取要测试Action
             ActionProxy proxy = getActionProxy("/example/example_listExample.action");
             ExampleAction ea = (ExampleAction) proxy.getAction();
             proxy.execute();

             //获取Action中执行结果
             JsonMsgBean jsonMsgBean = ea.getJsonMsgBean();
             logout.info(jsonMsgBean.msg);
         } catch (Exception e) {
             e.printStackTrace();
         }
    }

    @Override
    protected String[] getContextLocations() {
         //重设 Spring XML路径
         return new String[] { "classpath*:spring/appContext-*.xml" };
    }
}

END

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值