我有一个 junit 测试方法,它调用一个支持 bean 方法,如下所示:
myBackingBean.signup();
,在支持 bean 方法中有一个调用Faces.getLocale()
,它在行中给出空指针异常
UIViewRoot viewRoot = context.getViewRoot();
请告知如何能够在测试方法中设置语言环境并修复此错误。
解决方案如下:
1-将以下类添加到项目中:
public abstract class FacesContextMocker extends FacesContext {
private FacesContextMocker() {
}
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 mockFacesContext() {
FacesContext context = Mockito.mock(FacesContext.class);
setCurrentInstance(context);
Mockito.doAnswer(RELEASE).when(context).release();
return context;
}
}
2- 在@Before 中使用以下代码进行测试:
FacesContext facesContext = FacesContextMocker.mockFacesContext();
UIViewRoot uiViewRoot = Mockito.mock(UIViewRoot.class);
Mockito.when(facesContext.getCurrentInstance().getViewRoot())
.thenReturn(uiViewRoot);
Mockito.when(
facesContext.getCurrentInstance().getViewRoot().getLocale())
.thenReturn(new Locale("en"));