我正在爲使用Struts2,Spring和Hibernate使用JUnit的項目編寫集成測試用例。StrutsSpringTestCase - 幾個上下文 - 如何按順序實例化它們
我的測試課程延伸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
。但不知道爲什麼它在那裏。它不是空的。它還有其他的關鍵/價值。
嗯。應用程序檢查會話中的值。如果沒有,那麼該動作將不會被執行。所以我正在創建一個會話並手動進行。有了這個,它似乎照顧了「登錄」/「會話」部分,但這個getActionMapping事情似乎並不奏效。 – 2014-10-31 21:08:40
您應該爲該操作提供配置,即在'struts.xml'中。 – 2014-10-31 21:15:31