Mocking FacesContext

前端 未结 7 1105
执念已碎
执念已碎 2021-02-18 19:20

I am trying to add some unit tests to a JSF application. This application didnt rely heavily on any best practices, so many service methods use the FacesContext to

7条回答
  •  北荒
    北荒 (楼主)
    2021-02-18 19:53

    Here's another way to use Mockito and reflection to mock FacesContext and to make sure normal calls to FacesContext.getCurrentInstance() returns the (mocked) instance you want:

    @Before
    public void setUp() {
    
        // Use Mockito to make our Mocked FacesContext look more like a real one
        // while making it returns other Mocked objects
        ExternalContext externalContext = Mockito.mock(ExternalContext.class);
        Flash flash = Mockito.mock(Flash.class);
        FacesContext facesContext = Mockito.mock(FacesContext.class);
        Mockito.when(facesContext.getExternalContext()).thenReturn(externalContext);
        Mockito.when(externalContext.getFlash()).thenReturn(flash);
    
        // Use Java reflection to set the FacesContext to our Mock, since
        // FacesContext.setCurrentInstance() is protected.
        try {
            Method setter = FacesContext.class.getDeclaredMethod("setCurrentInstance", new Class[]{FacesContext.class});
            setter.setAccessible(true);
            setter.invoke(null, new Object[]{facesContext});
        } catch (Exception e) {
            System.err.println("Exception in reflection-based access to FacesContext");
            e.printStackTrace();
        }
    }
    

    (This is adapted / extended from @McDowell's answer below.)

提交回复
热议问题