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?
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