How to mock getApplicationContext

后端 未结 2 397
[愿得一人]
[愿得一人] 2020-12-23 22:41

I have an application that stores app context information. The app context information is shared between activities in MyApp class which extends Application class.

2条回答
  •  鱼传尺愫
    2020-12-23 23:09

    My problem was not exactly the same, but similar. Here is what worked for me.

    Firstly, at a class level for the test

    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest({CustomApp.class, AppUtils.class})
    public class CustomClientTest {
    
        @Mock
        Context mockContext;
    
        @Mock
        MainActivity mainActivityMock;
    

    then the setup()

    @Before
    public void setUp() throws Exception {
        PowerMockito.mockStatic(CustomApp.class);
        PowerMockito.mockStatic(AppUtils.class);
        when(CustomApp.getAppContext()).thenReturn(mockContext);
        when(webViewMock.getContext()).thenReturn(mainActivityMock);
    }
    

    and finally in the test itself

    @Test
    public void testShouldDoMyMethodRight() {
        // true tests
        assertTrue(customClient.shouldDoMethod(webViewMock, Constants.HAPPY_PATH));
        assertTrue(customClient.shouldOverrideUrlLoading(webViewMock, Constants.SPECIAL_PATH));
    }
    

提交回复
热议问题