问题:测试期间Struts ActionContext为空

使用Struts2 JUnit插件,我需要进行以下测试:

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();

  }

}


这两个相关的类如下:

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");
  }
}


我正在尝试用"application"模拟ActionContextHashMap对象。
值是在测试中设置的,但是一旦代码在BaseAction中执行,则值为null
这里有类似的问题(link),但对于我而言,答案不正确。

是否创建了其他ActionContext?如果可以,如何将变量传递给BaseAction

最佳答案

在操作执行期间创建操作上下文。您应该检查此代码以证明概念。

@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);
}


关于模板


  applyAdditionalParams(ActionContext)可以被覆盖
  子类中提供其他参数和设置
  动作调用

10-06 05:52