如何在junit测试中设置jsf语言环境?

时间:2013-07-26 13:42:54

标签: jsf junit mocking mockito jsf-2.2

我有一个junit测试方法,它调用一个支持bean方法,如下所示:

myBackingBean.signup();

,在支持bean方法中,调用Faces.getLocale()并在行中提供空指针异常

UIViewRoot viewRoot = context.getViewRoot();

请告知如何在测试方法中设置区域设置并修复此错误。

1 个答案:

答案 0 :(得分:2)

解决方案如下:

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"));