Mocking FacesContext

前端 未结 7 1077
执念已碎
执念已碎 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:59

    I give you an example to mock FacesConext without using PowerMockito. The idea is to extend a simple class from Facescontext, and change the current instance using protected static method setCurrentInstance:

    import javax.faces.context.FacesContext;
    import javax.servlet.ServletContext;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.mockito.Mock;
    import org.mockito.MockitoAnnotations;
    
    import com.sun.faces.config.InitFacesContext;
    
    public class DummyTest {
    
        @Mock
        private FacesContext context;
    
        @Before
        public void before(){
            MockitoAnnotations.initMocks(this);
            ServletContext sc = mock(ServletContext.class);
            new FakeContext(sc);
            assertEquals(context, FacesContext.getCurrentInstance());
        }
    
        @Test
        public void dummy(){
    
        }
    
        private class FakeContext extends InitFacesContext{
    
            public FakeContext(ServletContext sc) {
                super(sc);
                setCurrentInstance(context);
            }
    
        }
    
    }
    

提交回复
热议问题