JavaEEマネージドBeanに次のコードがあります。
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を外部コンテキストに注入するにはどうすればよいですか?
助けてくれてありがとう。
答え
コントローラコードが間違っています。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();