struts2 action测试用例

这篇文章主要内容是使用junit对struts2的action进行测试。

 

必须的包:

spring-core-2.5.6.jar

spring-test-2.5.6.jar

struts2-junit-plugin-2.2.1.1.jar

 

 

注:测试action ,需用到spring。

 

主要的测试方法:

测试用例需继承 StrutsTestCase

重写setupBeforeInitDispatcher方法,相当与Beforeclass

 

 

 

方法描叙
executeAction(String)

根据action的URL链接,输出action的结果流数据(结果类型不是SUCCESS,可以是FreeMarker, velocity, JSP等)

getActionProxy(String)生成一个action的代理
injectStrutsDependencies(object)注入一个依赖对象
getActionMapping(String)获得ActionMapping
findValueAfterExecute(String)action执行之后,从值栈中取值
属性描叙
MockHttpServletRequest requestrequset传递给struts2
MockHttpServletResponse response用于测试struts2输出
MockServletContext servletContexThe servlet context 传递给struts2

 

用例:

 

public class TestAction extends ActionSupport {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

junit:

 

package org.apache.struts2;

import org.apache.struts2.dispatcher.mapper.ActionMapping;

import java.util.HashMap;
import java.io.UnsupportedEncodingException;

import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.Action;

import javax.servlet.ServletException;

public class StrutsTestCaseTest extends StrutsTestCase {
    public void testGetActionMapping() {
        ActionMapping mapping = getActionMapping("/test/testAction.action");
        assertNotNull(mapping);
        assertEquals("/test", mapping.getNamespace());
        assertEquals("testAction", mapping.getName());
    }

    public void testGetActionProxy() throws Exception {
        //set parameters before calling getActionProxy
        request.setParameter("name", "FD");
        
        ActionProxy proxy = getActionProxy("/test/testAction.action");
        assertNotNull(proxy);

        TestAction action = (TestAction) proxy.getAction();
        assertNotNull(action);

        String result = proxy.execute();
        assertEquals(Action.SUCCESS, result);
        assertEquals("FD", action.getName());
    }

    public void testExecuteAction() throws ServletException, UnsupportedEncodingException {
        String output = executeAction("/test/testAction.action");
        assertEquals("Hello", output);
    }

    public void testGetValueFromStack() throws ServletException, UnsupportedEncodingException {
        request.setParameter("name", "FD");
        executeAction("/test/testAction.action");
        String name = (String) findValueAfterExecute("name");
        assertEquals("FD", name);
    }
}

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值