4

in my test method i want to be able to call Ajax.oncomplete which internally make calls to:

OmniPartialViewContext.getCurrentInstance 

please advise how to do that.

Mahmoud Saleh
  • 31,861
  • 113
  • 313
  • 484

1 Answers1

2

I have accomplished that as follows:

1- use FacesContextMocker class:

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- mock OmniPartialViewContext the object as follows:

FacesContext facesContext = FacesContextMocker.mockFacesContext();

        // mocking omnifaces OmniPartialViewContext to test Ajax.oncomplete
        OmniPartialViewContext omniPartialViewContext = Mockito
                .mock(OmniPartialViewContext.class);
        Map<Object, Object> map = facesContext.getCurrentInstance()
                .getAttributes();
        map.put(OmniPartialViewContext.class.getName(), omniPartialViewContext);
        Mockito.when(facesContext.getCurrentInstance().getAttributes())
                .thenReturn(map);
Mahmoud Saleh
  • 31,861
  • 113
  • 313
  • 484
  • Indeed, I was about to post a comment that it's just stored as `FacesContext` attribute with `OmniPartialViewContext.class.getName()` as key. – BalusC Jul 27 '13 at 13:34