我正在为使用 JUnit 的 Struts2、Spring、Hibernate 的项目编写集成测试用例。
我的测试类扩展了StrutsSpringTestCase
. 应用程序需要登录/会话来调用任何操作。以下是代码:
@Test
public void testGetActionProxy() throws Exception {
ActionProxy proxy;
String result;
ActionContext.getContext().setSession(createUserSession()); // Not sure if this is needed here. But in order to get the session working, I need this.
proxy = initAction("cInfo");
assertNotNull(proxy);
CustInfo action = (CustInfo) proxy.getAction();
result = proxy.execute();
assertEquals(Action.SUCCESS, result);
}
initAction()
方法:
private ActionProxy initAction(String actionUri) {
ActionProxy proxy = getActionProxy(actionUri);
ActionContext.setContext(proxy.getInvocation().getInvocationContext()); // I tried this line of code to get the ServletActionContext.getMapping().getName() to work. But no use.
ActionContext actionContext = proxy.getInvocation().getInvocationContext();
actionContext.setSession(createUserSession()); // This is for setting a session
return proxy;
}
在使用此方法之前,它会加载所有配置文件。struts.xml
jpaContext.xml
,beans.xml
等。
我的 Action 类CustInfo
实现ServletRequestAware
了,它有一个方法getActionName
,如下所示:
return ServletActionContext.getActionMapping().getName();
当我调用时会调用它result = proxy.execute();
。所以请求失败。
问题1:为什么会返回null
?我认为ServletActionContext
是自动启动的,所以它应该返回一个值。但它不是。如果它没有初始化,初始化的正确位置在哪里以及如何初始化?
getActionProxy
我在通话后尝试了以下操作。但它仍然没有工作。
ServletActionContext.setContext(proxy.getInvocation().getInvocationContext());
问题2:要设置会话,之前getActionProxy()
,我必须打电话,
ActionContext.getContext().setSession(createUserSession());
再一次,之后getActionProxy
ActionContext actionContext = proxy.getInvocation().getInvocationContext();
actionContext.setSession(createUserSession());
设置会话。我想,这里有问题。
问题 3:看起来,这里有几个上下文在起作用applicationContext
:ActionContext
ServletContext
和ServletActionContext
。
当我的测试类扩展StrutsSpringTestCase
类时,我猜applicationContext
是初始化了。但我不确定其他情况。在哪里初始化它们?
编辑:
对源代码的进一步调查揭示了一个问题。当我调用时ServletActionContext.getActionMapping()
,在内部调用它ActionContext
的get()
方法。
public Object get(String key) {
return context.get(key);
}
context
是一个对象的映射,它在其中寻找struts.actionMapping
不存在的键的值。所以,返回null
。但不知道为什么它在那里。它不是空的。它有其他键/值。