我假設你在談論HttpSession。
創建一個模擬會話,告訴模擬會話在其getAttribute方法被調用時使用被測對象使用的名稱時總是返回該對象,並將該模擬會話而不是真實的會話傳遞給被測對象。模擬API,如Mockito或EasyMock將有助於做到這一點。
編輯:假設你要測試的方法是這樣的:
public String foo() {
// some lines of code
MyObject o =
(MyObject)((HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest())
.getSession().getAttribute("myObject");
// some more lines of code, using o.
}
你可以重構它是這樣的:
public String foo() {
// some lines of code
MyObject o = getMyObjectFromSession();
// some more lines of code, using o.
}
protected MyObject getMyObjectFromSession() {
return (MyObject)((HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest())
.getSession().getAttribute("myObject");
}
然後你可以使用模擬框架做一些像這個(僞代碼):
// mockFoobar is the object to test. We just mock its getMyObjectFromSession method
FooBar mockFoobar = mock(Foobar.class);
MyObject objectInSession = new MyObject();
when(mockFoobar.getMyObjectFromSession()).thenReturn(objectInSession);
String s = mockFoobar.foo();
assertEquals("expected result", s);
你是如何在生產代碼訪問會話?注射?來自HTTP請求?會話範圍? – 2011-12-15 11:44:33
這裏的示例 - http://stackoverflow.com/questions/5136944/spring-test-session-scope-bean-using-junit關於使用會話 – 2011-12-15 11:53:13
問題更新。 – 2011-12-15 11:58:47