我正在为使用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
。但不确定它为什么会在那里。它不是空的。它有其他键/值。
问题的答案:
ServletActionContext.getActionMapping()
从动作上下文返回映射,如果没有设置,则获得null
。
您不应该手动设置会话,会话是在执行操作时创建的。
不要弄乱不同的类ActionContext
、ServletContext
和ServletActionContext
。初始化这些对象不应该做任何事情,因为它是由超类StrutsSpringTestCase
完成的。
public void testGetActionMapping() {
ActionMapping mapping = getActionMapping("/cInfo.action");
assertNotNull(mapping);
assertEquals("/", mapping.getNamespace());
assertEquals("cInfo", mapping.getName());
}
public void testGetActionProxy() throws Exception {
ActionProxy proxy = getActionProxy("/cInfo.action");
assertNotNull(proxy);
CustInfo action = (CustInfo) proxy.getAction();
assertNotNull(action);
String result = proxy.execute();
assertEquals(Action.SUCCESS, result);
}