I have an application that stores app context information. The app context information is shared between activities in MyApp class which extends Application class.
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));
}