我正在通过 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测试过程中,出现了这个Null Pointer。
我的测试类如下所示:
@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 吗?