Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

The Struts 2 Action doesn't expose HTTP in its signature. When access to HTTP resources is needed, references to these resources can be injected at runtime, but, to the Action, the servlet resources appear as ordinary Maps. When running tests outside of the framework, the test scaffolding can create and set a Map with whatever objects are needed by the test.

There are several approaches to unit testing Struts 2-based applications, whether using JUnit or TestNG. Two popular techniques are direct Action invocation and testing interceptors and result-types independently. We will demonstrate both approaches using JUnit 3.

...

Code Block
java
java
titleTest for ParametersInterceptor
public void testDoesNotAllowMethodInvocations() {
    Map params = new HashMap();
    params.put("@java.lang.System@exit(1).dummy", "dumb value");

    HashMap extraContext = new HashMap();
    extraContext.put(ActionContext.PARAMETERS, params);

    try {
        ActionProxy proxy = ActionProxyFactory.getFactory().
               createActionProxy("", MockConfigurationProvider.MODEL_DRIVEN_PARAM_TEST, extraContext);
        assertEquals(Action.SUCCESS, proxy.execute());

        ModelDrivenAction action = (ModelDrivenAction) proxy.getAction();
        TestBean model = (TestBean) action.getModel();

        String property = System.getProperty("action.security.test");
        assertNull(property);
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}

(lightbulb) The framework also providesbuiltprovides built-in support for JUnit 3.8 via an abstract StrutsTestCase, which provides common Struts variables and setup code.