struts2 action测试用例
http://hezhong002.iteye.com/blog/1108645- 博客分类:
- java
这篇文章主要内容是使用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 request | requset传递给struts2 |
MockHttpServletResponse response | 用于测试struts2输出 |
MockServletContext servletContex | The 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);
- }
- }
评论
如果能的话,能否给出点提示啊
功能测试中数据库操作是写mock对象的,
如果你要执行真实的数据库操作,数据是不会回滚的。
如果能的话,能否给出点提示啊