2013-01-08 103 views
0

我在一個Java EE下面的代碼託管bean:的JUnit測試FacesContext.getExternalContext

FacesContext context = facesContextProvider.getCurrentInstance(); 
HttpServletResponse response = (HttpServletResponse) context.getExternalContext(); 

哪裏facesContextProvider是返回faces上下文(用於模擬測試非常有用)的自定義類。

我想知道如何在使用mockito的JUnit中進行測試。我正試着組合:

FacesContextProvider mockFacesContextProvider = mock(FacesContextProvider.class); 
when(mockFacesContextProvider.getCurrentInstance()).thenReturn(mockFacesContext); 
// this line is wrong ~> when(mockFacesContext.getExternalContext()).thenReturn((ExternalContext) new MockHttpServletResponse()); 

如何注入某種模擬或自定義HttpServletResponse到我的外部上下文中?

感謝您的幫助。

ANSWER

我的控制器代碼是錯誤的。您可以使用ExternalContext來執行您所需的任何操作。因此,在控制器,它實際上應該是:

FacesContext facesContext = facesContextProvider.getCurrentInstance(); 
ExternalContext externalContext = facesContext.getExternalContext(); 
externalContext.responseReset(); 

如果你還想要回應,你可以得到它:

HttpResponse response = externalContext.getResponse(); 

然後將單元測試工具是:

mockFacesContextProvider = mock(FacesContextProvider.class); 
mockFacesContext = mock(FacesContext.class); 
mockExternalContext = mock(ExternalContext.class); 
mockHttpSession = mock(HttpSession.class); 
when(mockFacesContextProvider.getCurrentInstance()).thenReturn(mockFacesContext); 
when(mockFacesContext.getExternalContext()).thenReturn(mockExternalContext); 
when(mockExternalContext.getSession(true)).thenReturn(mockHttpSession); 

然後單元測試代碼將是:

verify(mockExternalContext).responseReset(); 
+1

我不能模擬ExternalContext.class,因爲它是抽象的......你是怎麼做到的? – karmapolice

回答

0
FacesContextProvider mockFacesContextProvider = mock(FacesContextProvider.class); 
HttpServletResponse mockResponse = mock(HttpServletResponse.class); 
when(mockFacesContextProvider.getCurrentInstance()).thenReturn(mockFacesContext); 
when(mockFacesContext.getExternalContext()).thenReturn(mockResponse);  
+0

感謝您的答案。我也嘗試過這個失敗。它實際上會是HttpServletResponse mockResponse = mock(HttpServletResponse.class);當(mockFacesContext.getExternalContext())。然後返回((ExternalContext)mockResponse),但是,這會拋出一個類拋出異常 – dev

+0

我有點困惑。 ExternalContext是HttpServletResponse的子類嗎?如果是這樣,我認爲你不需要原始代碼中的演員;你也需要模擬'ExternalContext',而不是'HttpServletResponse'。 –

+0

是的,就是這樣。我會更新原始問題,並在您獲得答案後向您提供答案。 – dev