ActionContext.getContext().getParameters() returns null during StrutsJUnit4TestCase

廉价感情. 提交于 2019-12-10 18:58:34

问题


I am running a JUnit test via maven where a struts action java method is being tested that makes the following call:

// Gets this from the "org.apache.struts2.util.TokenHelper" class in the struts2-core jar
String token = TokenHelper.getTokenName();

Here is the method in "TokenHelper.java":

/**
 * Gets the token name from the Parameters in the ServletActionContext
 *
 * @return the token name found in the params, or null if it could not be found
 */
public static String getTokenName() {

    Map params = ActionContext.getContext().getParameters();

    if (!params.containsKey(TOKEN_NAME_FIELD)) {
        LOG.warn("Could not find token name in params.");

        return null;
    }

    String[] tokenNames = (String[]) params.get(TOKEN_NAME_FIELD);
    String tokenName;

    if ((tokenNames == null) || (tokenNames.length < 1)) {
       LOG.warn("Got a null or empty token name.");

        return null;
    }

    tokenName = tokenNames[0];

    return tokenName;
}

The 1st line in this method is returning null:

Map params = ActionContext.getContext().getParameters();

The next LOC down, "params.containKey(...)" throws a NullPointerException because "params" is null.

When this action is called normally, this runs fine. However, during the JUnit test, this Null Pointer occurs.

My test class looks like this:

@Anonymous
public class MNManageLocationActionTest extends StrutsJUnit4TestCase {

    private static MNManageLocationAction action;

    @BeforeClass
    public static void init() {
        action = new MNManageLocationAction();
    }

    @Test
    public void testGetActionMapping() {
        ActionMapping mapping = getActionMapping("/companylocation/FetchCountyListByZip.action");
        assertNotNull(mapping);
    }

    @Test
    public void testLoadStateList() throws JSONException {
        request.setParameter("Ryan", "Ryan");

        String result = action.loadStateList();

        assertEquals("Verify that the loadStateList() function completes without Exceptions.", 
              result, "success");
    }
}

The ActionContext.getContext() is at least no longer null after I switched to using StrutsJUnit4TestCase.

Any idea why .getParameters() is returning null?


回答1:


You need to initialize parameters map by yourself inside your test method. Additionally if you want to get token name you need to put it in parameters map.

Map<String, Object> params = new HashMap<String, Object>();
params.put(TokenHelper.TOKEN_NAME_FIELD, 
                       new String[] { TokenHelper.DEFAULT_TOKEN_NAME });
ActionContext.getContext().setParameters(params);


来源:https://stackoverflow.com/questions/21291106/actioncontext-getcontext-getparameters-returns-null-during-strutsjunit4testc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!