`
hilliate
  • 浏览: 135056 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

【转】:Unit Testing Struts 2 Actions

    博客分类:
  • Java
阅读更多

 

from:http://glindholm.wordpress.com/2008/06/30/unit-testing-struts-2-actions/

实在没办法,该网站被墙,转载学习

 

Hopefully this will help others who are trying to unit test Struts 2 Actions.

 

My goal is to be able to unit test my actions in the full Struts 2 context with the Interceptor stack being run which includes validation.  The big advantage of this type of testing is that it allows you test you validation logic, the Interceptor configuration for you actions, and the results configuration.

 

The current information on Struts 2 website regarding unit testing was not very helpful.  The guides page has 2 links to external blogs with some example code for unit testing with Spring.  I used these as starting points but since I’m not using Spring and the examples were heavily dependent on Spring I ended up spending a lot of time in the debugger figuring out how to make this work.

 

Below is my StrutsTestContext class it makes use of Mockrunner mock Http Servlet classes (mockrunner-servlet.jar).  (If you wish to use a different mock package it should be easy enough to make the change.)

 

The way this works is you first have to create a Dispatcher which reads your struts configuration. You then use the Dispatcher to create anActionProxy with the desired request parameters and session attributes.  The ActionProxy will give you access to the Action object so you can set properties or inject mock objects for your test.  You next execute the ActionProxy to run the Interceptor stack and your action, this returns the result so you can test it for correctness.  You can also test the mock Http servlet objects to ensure other result effects have occured (e.g. a session attribute was changed.)

 

This has been updated for Struts 2.1.6 on 3/5/2009.

 

 

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package test.struts;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import com.mockrunner.mock.web.MockHttpServletRequest;
import com.mockrunner.mock.web.MockHttpServletResponse;
import com.mockrunner.mock.web.MockHttpSession;
import com.mockrunner.mock.web.MockServletContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;

public class StrutsTestContext
{
    public StrutsTestContext(Dispatcher dispatcher,
                             MockServletContext servletContext)
    {
        this.dispatcher = dispatcher;
        this.mockServletContext = servletContext;
    }

    private Dispatcher              dispatcher;
    private MockServletContext      mockServletContext;
    private MockHttpServletRequest  mockRequest;
    private MockHttpServletResponse mockResponse;

    public static Dispatcher prepareDispatcher()
    {
        return prepareDispatcher(null, null);
    }

    public static Dispatcher prepareDispatcher(
           ServletContext servletContext,
           Map<String, String> params)
    {
        if (params == null)
        {
            params = new HashMap<String, String>();
        }
        Dispatcher dispatcher = new Dispatcher(servletContext, params);
        dispatcher.init();
        Dispatcher.setInstance(dispatcher);
        return dispatcher;
    }

    public static ActionProxy createActionProxy(
          Dispatcher dispatcher,
          String namespace,
          String actionName,
          HttpServletRequest request,
          HttpServletResponse response,
          ServletContext servletContext) throws Exception
    {
        // BEGIN: Change for Struts 2.1.6
        Container container = dispatcher.getContainer();
        ValueStack stack = container.getInstance(ValueStackFactory.class).createValueStack();
        ActionContext.setContext(new ActionContext(stack.getContext()));
        // END: Change for Struts 2.1.6

        ServletActionContext.setRequest(request);
        ServletActionContext.setResponse(response);
        ServletActionContext.setServletContext(servletContext);

        ActionMapping mapping = null;
        return dispatcher.getContainer()
           .getInstance(ActionProxyFactory.class)
           .createActionProxy(
            namespace,
            actionName,
            dispatcher.createContextMap(
                request, response, mapping, servletContext),
            true, // execute result
            false);
    }

    public ActionProxy createActionProxy(
               String namespace,
               String actionName,
               Map<String, String> requestParams,
               Map<String, Object> sessionAttributes) throws Exception
    {
        mockRequest = new MockHttpServletRequest();
        mockRequest.setSession(new MockHttpSession());
        mockResponse = new MockHttpServletResponse();

        if (requestParams != null)
        {
            for (Map.Entry<String, String> param :
                       requestParams.entrySet())
            {
                mockRequest.setupAddParameter(param.getKey(),
                                              param.getValue());
            }
        }
        if (sessionAttributes != null)
        {
            for (Map.Entry<String, ?> attribute :
                      sessionAttributes.entrySet())
            {
                mockRequest.getSession().setAttribute(
                    attribute.getKey(),
                    attribute.getValue());
            }
        }

        return createActionProxy(
            dispatcher, namespace, actionName,
            mockRequest, mockResponse, mockServletContext);
    }

    public Dispatcher getDispatcher()
    {
        return dispatcher;
    }

    public MockHttpServletRequest getMockRequest()
    {
        return mockRequest;
    }

    public MockHttpServletResponse getMockResponse()
    {
        return mockResponse;
    }

    public MockServletContext getMockServletContext()
    {
        return mockServletContext;
    }

}

 

 

Here is an example of using this class to unit test a Login Action.

 

/*
** Create a Dispatcher.
** This is an expensive operation as it has to load all
** the struts configuration so you will want to reuse the Dispatcher for
** multiple tests instead of re-creating it each time.
**
** In this example I'm setting configuration parameter to override the
** values in struts.xml.
*/
  HashMap<String, String> params = new HashMap<String, String>();
  // Override struts.xml config constants to use a guice test module
  params.put("struts.objectFactory", "guice");
  params.put("guice.module", "test.MyModule");

  MockServletContext servletContext = new MockServletContext();
  Dispatcher dispatcher = StrutsTestContext.prepareDispatcher(
       servletContext, params);

/*
**  Create an ActionProxy based on the namespace and action.
**  Pass in request parameters and session attributes needed for this
**  test.
*/
  StrutsTestContext context = new StrutsTestContext(
      dispatcher, servletContext);
  Map<String, String> requestParams = new HashMap<String, String>();
  Map<String, Object> sessionAttributes = new HashMap<String, Object>();
  requestParams.put("username", "test");
  requestParams.put("password", "test");

  ActionProxy proxy = context.createActionProxy(
      "/admin",      // namespace
      "LoginSubmit", // Action
      requestParams,
      sessionAttributes);

  assertTrue(proxy.getAction() instanceof LoginAction);

  // Get the Action object from the proxy
  LoginAction action = (LoginAction) proxy.getAction();

  // Inject any mock objects or set any action properties needed
  action.setXXX(new MockXXX());

  // Run the Struts Interceptor stack and the Action
  String result = proxy.execute();

  // Check the results
  assertEquals("success", result);

  // Check the user was redirected as expected
  assertEquals(true, context.getMockResponse().wasRedirectSent());
  assertEquals("/admin/WelcomeUser.action",
      context.getMockResponse().getHeader("Location"));

  // Check the session Login object was set
  assertEquals(mockLogin,
      context.getMockRequest().getSession().getAttribute(
         Constants.SESSION_LOGIN));

 

 

 

 

分享到:
评论

相关推荐

    struts2常用包

    Struts2是一个强大的Java EE应用程序框架,主要用于构建Web应用程序。它基于MVC(Model-View-Controller)设计模式,提供了一种结构化的、灵活的方式来组织和控制应用的业务逻辑。Struts2的核心在于其Action类,它...

    struts2的struts.properties配置文件详解

    Struts2的Struts.properties配置文件详解 Struts2是一个基于MVC模式的Web应用程序框架,它提供了一个名为Struts.properties的配置文件,该文件用于配置Struts2的各种参数和设置。下面将对Struts.properties配置文件...

    struts2.3.34依赖jar包

    2. **插件支持**:Struts2提供了丰富的插件来扩展其功能,例如`struts2-convention-plugin.jar` 提供了基于约定优于配置的规则,使得类和方法自动映射到URL。 3. **结果类型**:`struts2-dojo-plugin.jar` 或 `...

    struts2-core-2.0.11源码

    2. **配置管理(Configuration Manager)**:Struts2通过`org.apache.struts2.config`包中的类来管理配置信息,包括XML配置文件和注解配置,这些类解析配置并创建Action和Interceptor实例。 3. **Action上下文...

    struts2的配置信息

    Struts2是一个强大的Java web应用程序框架,用于构建和部署可维护、高性能的MVC(Model-View-Controller)架构的应用程序。它简化了MVC设计模式的实现,并提供了丰富的功能来处理请求、响应以及业务逻辑的集成。在这...

    Struts2 ConverterType类型转换 案例源码

    Struts2是一个强大的MVC框架,它在处理用户请求时提供了丰富的功能,其中包括类型转换(Converter)。类型转换是Struts2框架中一个重要的特性,它允许我们把前端表单提交的数据自动转换为后端Java对象的属性。在这个...

    配置struts2需要的资源包

    - **插件支持**:Struts2提供了许多插件,如Struts2-convention-plugin.jar用于自动配置,Struts2-dojo-plugin.jar用于与Dojo库集成,Struts2-json-plugin.jar用于JSON支持等。 - **依赖的Servlet API**:由于...

    struts2入门例子

    5. **XWork2**:Struts2是在XWork框架的基础上发展起来的,XWork提供了Action管理和执行的核心机制,包括ActionContext、ValueStack等关键组件。 6. **运行流程**:当一个请求到达服务器,Struts2框架会解析`struts...

    struts2图片上传并预览

    创建一个名为`UploadAction`的类,该类需要继承`org.apache.struts2.actions.FileUploadAction`,并在其中定义一个`List&lt;File&gt;`类型的属性,用于接收上传的文件。 ```java public class UploadAction extends ...

    语言程序设计资料:struts2基本配置使用手册.doc

    struts.xml 文件的内容包括 Struts 2.0 的配置信息,如 packages、actions、results 等。 本文提供了 Struts 2.0 的基本配置使用手册,旨在帮助读者快速上手 Struts 2.0,并应用于实际项目中。 知识点: * ...

    Struts 2 in Action (May 2008).pdf

    5. **配置和注解**:Struts 2支持XML配置和注解配置两种方式,使得开发者可以根据项目需求选择合适的配置方式。书中会对比和解释这两种配置方法的使用场景和优缺点。 6. **国际化和本地化**:Struts 2提供了便捷的...

    struts2从入门到精通总结(备忘)

    接口或继承`org.apache.struts2.actions.support.AbstractActionSupport`基类来创建。Action类中的方法通常会返回一个字符串,这个字符串会被解析为结果类型,决定跳转到哪个页面。 四、数据操作 Struts2支持多种...

    org.apache.struts缺少所需包

    import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.actions.DispatchAction等缺少

    struts2inaction

    - **定义**:Struts 2是基于Struts 1的一个全新版本,它不仅继承了Struts 1的一些优秀特性,而且在很多方面进行了重大的改进和完善。 - **特点**:Struts 2是一个用于开发Java Web应用程序的开源框架,它采用MVC...

    Struts2 英文教程

    #### Actions:Struts2的核心组件 Actions是Struts2框架的基本构建块,用于处理来自用户界面的请求并返回响应结果。它们通常是一些简单的Java类,不需要继承特定的基类或实现接口。下面是一个简单的UserAction示例...

    strutsActions 测试用例

    StrutsActions是Apache Struts框架的核心组成部分,它定义了用户交互与业务逻辑之间的桥梁。Struts是一个开源的Java EE Web应用程序框架,它基于Model-View-Controller(MVC)设计模式,旨在简化创建用户接口、处理...

    Struts2 In Action

    - **第1章:Struts2:现代Web应用框架**(第3页起) - **章节概述**:本章介绍了Struts2框架的基本概念,包括其设计理念、特点以及与其他Web框架的比较。通过本章的学习,读者将对Struts2有一个初步的认识,并了解...

    Struts2InAction中文+源代码

    1. **动作(Actions)与结果(Results)**:Struts2的动作类是业务逻辑的载体,它处理HTTP请求,并根据执行的结果导向不同的视图。结果可以是JSP、Freemarker模板或者重定向到其他URL。 2. **拦截器(Interceptors...

Global site tag (gtag.js) - Google Analytics