0

我在 Java EE 托管 bean 中有以下代码:

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

facesContextProvider 是一个自定义类,用于返回人脸上下文(用于模拟测试)。

我想知道如何使用 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();
4

1 回答 1

0
FacesContextProvider mockFacesContextProvider = mock(FacesContextProvider.class);
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
when(mockFacesContextProvider.getCurrentInstance()).thenReturn(mockFacesContext);
when(mockFacesContext.getExternalContext()).thenReturn(mockResponse);    
于 2013-01-08T04:36:52.580 回答