使用Struts2的Junit Plugin测试Action是非常的方便的,如果在开发中采用TDD模式的话推荐使用。不说废话了,直入主题,已具体实例说话!
1、在原有的Struts2工程加入JUnit Plugin和它依赖的Spring包:
- struts2-junit-plugin-2.1.8.jar
- org.springframework.core-3.0.3.RELEASE.jar
- org.springframework.test-3.0.3.RELEASE.jar
2、新建个Action,我这里采用的Annotation的方式,可以实现零配置。TestAction.java
- @Result(location = "/index.jsp")
- public class TestAction extends ActionSupport {
- private String param;
- public String execute() {
- return SUCCESS;
- }
- public String getParam() {
- return param;
- }
- public void setParam(String param) {
- this.param = param;
- }
- }
3、在工程中添加JUnit包(此步骤略了,搞不定这部的就不要看此篇文章啦!),创建TestCase,TestActionTest.java
- import java.robinleex.action.TestAction;
- import org.apache.struts2.StrutsTestCase;
- import org.junit.Test;
- import com.opensymphony.xwork2.ActionProxy;
- public class TestActionTest extends StrutsTestCase {
- @Test
- public void testExecute() throws Exception {
- ActionProxy proxy = null;
- TestAction test = null;
- request.setParameter("param", "test...");
- proxy = getActionProxy("/test.action");
- test = (TestAction)proxy.getAction();
- String result = proxy.execute();
- assertEquals("success", result);
- assertEquals("test...", test.getParam());
- }
- }
跑起来就可以了,非常好用,这个示例测试在Action当中传入一个参数并取出参数值。JUnit Plugin会模拟Servlet容器,模拟出 HttPServletRequest,HttpServletResponse,ServletContext,PageContext...
示例源码请见附件!
有问题可以联系作者,联系方式:robinleex@gmail.com
【编辑推荐】