1

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 to pass a variable to the BaseAction?

Roman C
  • 49,761
  • 33
  • 66
  • 176
dingdingding
  • 1,411
  • 1
  • 15
  • 23

1 Answers1

0

ActionContext 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

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • Thanks for clearing that up for me. So is there any way at all to set a value in "/home" action's ActionContext before executeAction("/home") is called? – dingdingding Aug 22 '14 at 13:39
  • The last method should be called before your action is executed. So you can put your params there. Before `executeAction` you have not an actual action context. – Roman C Aug 22 '14 at 14:00