Struts2 JUnit ActionContext对象

问题:测试期间Struts ActionContext为null

使用Struts2 JUnit插件我有以下测试:

 public class MainActionIT extends StrutsJUnit4TestCase { @Test public void testAction() { Map application = new HashMap(); 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"); } } 

我正在尝试使用HashMap模拟ActionContext"application"对象。 值在测试中设置,但是一旦代码在BaseAction执行,则值为null 。 类似的问题在这里( 链接 ),但在我的情况下答案是不正确的。

是否创建了不同的ActionContext ? 如果是这样,我如何将变量传递给BaseAction

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

 @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 application = new HashMap(); application.put("options","home"); context.put("application", application); } 

关于模板

applyAdditionalParams(ActionContext)可以在子类中覆盖,以提供在动作调用期间使用的其他参数和设置