java如何模拟来自Faces上下文和外部上下文的请求?
我有密码。java是这样的:
public void init() {
// Blah...
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); // line 10
HttpServletRequest request = (HttpServletRequest) context.getRequest(); // line 11
// Blah...
}
我也创建了FacesContextProvider类,这是我的FacesContextProvider。爪哇
public abstract class FacesContextProvider extends FacesContext {
private FacesContextProvider() {
}
private static final Release RELEASE = new Release();
private static class Release implements Answer<Void> {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
setCurrentInstance(null);
return null;
}
}
public static FacesContext getCurrentInstance() {
FacesContext context = Mockito.mock(FacesContext.class);
setCurrentInstance(context);
Mockito.doAnswer(RELEASE).when(context).release();
return context;
}
}
这是我的测试。爪哇
FacesContext mockFacesContext = FacesContextProvider.getCurrentInstance();
HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
ExternalContext mockExternalContext = Mockito.mock(ExternalContext.class);
when(mockFacesContext.getExternalContext()).thenReturn(mockExternalContext);
when(mockExternalContext.getRequest()).thenReturn(mockRequest);
// Run Test
mainBackingUnderTest.init(); // has been declare at top using @InjectMocks
当我运行测试时,MainBacking上出现了错误null。爪哇:请帮帮我。多谢各位
# 1 楼答案
谢谢你的回复,我通过阅读this article解决了我的问题。当我使用
FacesContextProvider
时,我不知道出了什么问题。我仍然有空错误,但是当我使用Omnifaces将模拟的FacesContext设置为测试用例中的当前实例时,空错误得到了解决。谢谢大家!# 2 楼答案
看着其中的this answer和article linked,我无法重现NPE。 我就是这样测试的: