Struts2 JUnit ActionContext objects

Deadly 提交于 2019-12-30 11:38:07

问题


Problem: Struts ActionContext is null during test

Using Struts2 JUnit plugin I have the following test:

public class MainActionIT extends StrutsJUnit4TestCase 
{
  @Test
  public void testAction() {
    Map<String, Object> application = new HashMap<String, Object>();
    application.put("options","home");
    ActionContext.getContext().put("application",application);
    ActionProxy proxy = getActionProxy("/home");
    String result = proxy.execute();

  }

}

The two related classes are as follows:

public class MainAction extends BaseAction 
{
  @Action(value = "/home", results = {@Result(name = "success", location = "home.jsp")}
  public String getHome()
  {
    Map options = getHomeOptions();
    return SUCCESS;
  }
}

public class BaseAction extends ActionSupport
{
  public Map getHomeOptions() 
  {
    return ActionContext.getContext().get("application").get("options");
  }
}

I'm trying to mock the "application" object of the ActionContext with a HashMap. Values are set in the test but once the code executes in BaseAction the values are null. Similar problem here (link) but the answer isn't correct in my case.

Is there a different ActionContext being created? If so how can I pass a variable to the BaseAction?


回答1:


Action context is created during the action execution. You should check this code to proof the concept.

@Test
public void shouldAdditionalContextParamsBeAvailable() throws Exception {
    // given
    String key = "application";
    assertNull(ActionContext.getContext().get(key));

    // when
    String output = executeAction("/home");

    // then
    assertNotNull(ActionContext.getContext().get(key));
}

@Override
protected void applyAdditionalParams(ActionContext context) {
    Map<String, Object> application = new HashMap<String, Object>();
    application.put("options","home");
    context.put("application", application);
}

About the template

applyAdditionalParams(ActionContext) Can be overwritten in subclass to provide additional params and settings used during action invocation



来源:https://stackoverflow.com/questions/25436615/struts2-junit-actioncontext-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!