`
hilliate
  • 浏览: 133493 次
  • 性别: 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));

 

 

 

 

分享到:
评论

相关推荐

    strutsActions 测试用例

    strutsActions 测试用例 strutsActions 测试用例

    struts2 chm 帮助文档

    struts2 chm 程序包 org.apache.struts2 接口概要 接口 说明 StrutsStatics Constants used by Struts. 类概要 类 说明 RequestUtils Request handling utility class. ServletActionContext Web-specific ...

    Software Testing using VisualStudio2012

    Chapter 2: Test Plan, Test Suite, and Manual Testing Chapter 3: Automated Tests Chapter 4: Unit Testing Chapter 5: Web Performance Test Chapter 6: Advanced Web Testing Chapter 7: Load Testing Chapter ...

    Playmaker v1.9.0.p20.zip

    The top-rated visual scripting tool for ...:: NGUI, 2DToolkit, Photon, iTween... :: Extend Playmaker with Custom Actions. :: Watch tutorials on our YouTube Channel. :: Join an active online community.

    struts2.0.jar

    · 易于测试: Struts 2 Actions独立于HTTP,因而与框架中立。无须使用模拟对象(mock object),就很容易测试。 · 使用注释: 使用Struts 2开发的应用可以使用Java 5注释,作为XML和Java属性配置之外的一个替代办法...

    Playmaker 1.9.0.p4.unitypackage 下载 不用代码制作游戏,支持unity3d 2018

    Playmaker 1.9.0.p4.unitypackage 支持5.x ...:: NGUI, 2DToolkit, Photon, iTween... :: Extend Playmaker with Custom Actions. :: Watch tutorials on our YouTube Channel. :: Join an active online community.

    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等缺少

    jobportal:使用JavaEE,Struts2,Hibernate和MySQL开发的Web应用程序

    工作机会 具有Struts2和Hibernate框架的JavaEE中的JobPortal。 Struts2 ... POJO forms and POJO actions - Struts2 has done away with the Action Forms that were an integral part of the Stru

    Playmaker 官方最新1.9.0 p4

    :: Download Action Packs for popular plugins: :: NGUI, 2DToolkit, Photon, iTween... :: Extend Playmaker with Custom Actions. :: Watch tutorials on our YouTube Channel. :: Join an active online ...

    更漂亮::hammer:Github Actions上的本机,极快的Prettier CLI

    :fire: Github Actions上的本机,快速的prettier CLI,使您可以在Github Actions上运行每个prettier CLI命令,而无需事先安装Node.js或任何依赖项。 平均完成时间:5-8秒-比自我实现的工作流程(启用缓存)快7倍。...

    ROS2官网教程学习笔记理解ROS2 actions动作

    ROS2官网教程学习笔记理解ROS2 actions动作背景准备条件学习内容1. 启动节点2. 使用 actions动作3. ros2 node info4. ros2 action list4.1 ros2 action list -t5. ros2 action info6. ros2 interface show7. ros2 ...

    Struts2 Convention Plugin中文文档 Annotion

    从struts2.1版本开始,Convention Plugin作为替换替换Codebehind Plugin来实现Struts2的零配置。 • 包命名习惯来指定Action位置 • 命名习惯制定结果(支持JSP,FreeMarker等)路径 • 类名到URL的约定转换 • 包名...

    struts2零配置个人整理文档

    默认包路径包含action,actions,struts,struts2的所有包都会被struts作为含有Action类的路径来搜索。你可以通过设置struts.convention.package.locators属性来修改这个配置。如: &lt;constant name="struts.convention....

    随时随地::rocket:使用GitHub Actions,npm,docker或bash自动进行版本控制,更改日志创建,README更新和GitHub发布

    随时随地::rocket:使用GitHub Actions,npm,docker或bash自动进行版本控制,更改日志创建,README更新和GitHub发布

    actions-netlify::rocket:从GitHub Actions进行Netlify部署

    用法# .github/workflows/netlify.ymlname : Build and Deploy to Netlifyon : push : pull_request :jobs : build : runs-on : ubuntu-18.04 steps : - uses : actions/checkout@v2 # ( Build to ./dist or other ...

    Playmaker v1.8.7.unitypackage

    playmaker最新1.8.7版 ...:: NGUI, 2DToolkit, Photon, iTween... :: Extend Playmaker with Custom Actions. :: Watch tutorials on our YouTube Channel. :: Join an active online community.

    github-actions-lab:@micnncim的GitHub Actions个人沙箱环境

    github-actions-lab:@micnncim的GitHub Actions个人沙箱环境

    Playmaker v1.8.6.unitypackage下载

    This extension requires one license per ...:: NGUI, 2DToolkit, Photon, iTween... :: Extend Playmaker with Custom Actions. :: Watch tutorials on our YouTube Channel. :: Join an active online community.

    深入浅出struts2

    │深入浅出STRUTS 2 Struts Ti却发现了二者在技术与开发人员这两个层面上的共同之处,不久之后,两个项目就在WebWork的技术基础上进行了合并2。 当我们说起WebWork的时候,我们实际上说的是两个项目——XWork和...

Global site tag (gtag.js) - Google Analytics