Struts2 JUnit ActionContext对象 [英] Struts2 JUnit ActionContext objects
问题描述
问题:Struts ActionContext
在测试期间为空
Problem: Struts ActionContext
is null during test
使用Struts2 JUnit插件我有以下测试:
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();
}
}
这两个相关课程如下:
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");
}
}
我正在尝试模拟 ActionContext的
使用application
对象 HashMap
。
在测试中设置值但是一旦代码在 BaseAction
中执行值为 null
。
此处类似问题(链接)但答案在我的情况下是不正确的。
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.
是否有不同的 ActionContext
正在创建?如果是这样,我如何将变量传递给 BaseAction
?
Is there a different ActionContext
being created? If so how can I pass a variable to the BaseAction
?
推荐答案
在操作执行期间创建操作上下文。您应该检查此代码以证明该概念。
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);
}
关于模板
applyAdditionalParams(ActionContext)
可以在子类中覆盖
,以提供
动作调用期间使用的其他参数和设置
applyAdditionalParams(ActionContext)
Can be overwritten in subclass to provide additional params and settings used during action invocation
这篇关于Struts2 JUnit ActionContext对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!