Struts ActionContext
在测试期间为 null
。
使用 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");
}
}
我正在尝试使用 HashMap
模拟 ActionContext
的 “application”
对象。
值是在测试中设置的,但是一旦代码在 BaseAction
中执行,这些值就是null
。
这里有类似的问题( link ),但在我的例子中答案不正确。
是否正在创建不同的ActionContext
?如果是这样,如何将变量传递给BaseAction
?
最佳答案
ActionContext
在操作执行期间创建。您应该检查此代码来证明这个概念。
@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)
Can be overwritten in subclass to provide additional params and settings used during action invocation
关于java - Struts2 JUnit ActionContext 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25436615/