我在一個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();
我不能模擬ExternalContext.class,因爲它是抽象的......你是怎麼做到的? – karmapolice