0
我有一个调用后台bean的方法如下JUnit测试方法:如何在junit测试中设置jsf语言环境?
myBackingBean.signup();
,在后台bean的方法有以Faces.getLocale()
一个电话,它给空指针异常的线
UIViewRoot viewRoot = context.getViewRoot();
请告知如何能够在测试方法中设置语言环境并修复此错误。
我有一个调用后台bean的方法如下JUnit测试方法:如何在junit测试中设置jsf语言环境?
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"));
很酷,很高兴你解决了它。 :) – elias
你应该嘲笑'Faces.getLocale()'方法。你在使用模拟库吗?如果是,哪一个?如果不是,你如何在测试中配置协作者? – elias
@elias,我正在使用mockito和powermock,请告诉我如何正确模拟Faces.getLocale()。 –