Mahmoud Saleh
Mahmoud Saleh

Reputation: 33615

How to set jsf locale in junit test?

i have a junit test method that calls a backing bean method as follows:

myBackingBean.signup();

, in the backing bean method there's a call to Faces.getLocale() and it gives null pointer exception in the line

UIViewRoot viewRoot = context.getViewRoot();

please advise how to be able to set locale in test method and fix this error.

Upvotes: 0

Views: 1324

Answers (1)

Mahmoud Saleh
Mahmoud Saleh

Reputation: 33615

solution was as follows:

1- add the following class to project:

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- In @Before for the test use the following code:

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

Upvotes: 2

Related Questions