I have code on MainBacking.java like this :
public void init() { // Blah... ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); // line 10 HttpServletRequest request = (HttpServletRequest) context.getRequest(); // line 11 // Blah... }
I made FacesContextProvider class too and here is my FacesContextProvider.java
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; } }
And here is my test.java
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
When I run the test i got error null on MainBacking.java:11 Please help me. Thank You.
Advertisement
Answer
Thank You for all response, I’ve solved my problem by reading this article. I didn’t know whats wrong when I’m using FacesContextProvider
I’m still got null error, but when I’m using Omnifaces to set the mocked FacesContext as current instance in my test-case, the null error was solved. Thank You!