gpt4 book ai didi

maven - ActionContext.getContext().getParameters() 在 StrutsJUnit4TestCase 期间返回 null

转载 作者:行者123 更新时间:2023-12-02 23:40:39 30 4
gpt4 key购买 nike

我正在通过 maven 运行 JUnit 测试,其中正在测试进行以下调用的 struts 操作 java 方法:

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

这是“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;
}

此方法中的第一行返回 null:

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

下一个 LOC,“params.containKey(...)”会抛出 NullPointerException,因为“params”为 null。

当正常调用此操作时,运行良好。然而,在JUnit测试过程中,出现了这个空指针。

我的测试类如下所示:

@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");
}
}

在我切换到使用 StrutsJUnit4TestCase 后,ActionContext.getContext() 至少不再为 null。

知道为什么 .getParameters() 返回 null 吗?

最佳答案

您需要在测试方法中自行初始化参数映射。此外,如果您想获取 token 名称,则需要将其放入参数映射中。

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

关于maven - ActionContext.getContext().getParameters() 在 StrutsJUnit4TestCase 期间返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21291106/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com