How do you get hold of an Android Context for a Junit test from a Java Project?

16,075

Solution 1

What about using AndroidTestCase instead of a JUnit test? AndroidTestCase will provide a Context with getContext() that can be used where it's needed.

Solution 2

Another way to access context from JUnit without extending AndroidTestCase is to use Rule to launch an activity under test. Rules are interceptors which are executed for each test method and will run before any of your setup code in the @Before method. Rules were presented as a replacement for the ActivityInstrumentationTestCase2.

@RunWith(AndroidJUnit4.class)
@SmallTest
public class ConnectivityTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void testIsConnected() throws Exception {
        Context context = mActivityRule.getActivity().getBaseContext();
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean connected = cm.getActiveNetworkInfo().isConnectedOrConnecting();
        Assert.assertEquals(connected, ConnectionUtils.isConnected(context));
    }
}

Solution 3

If your test is an instrumentation test (running on emulator or device), you can simply use

Context appContext = InstrumentationRegistry.getTargetContext();

The dependency is:

androidTestCompile 'com.android.support.test:runner:0.5'
Share:
16,075
jax
Author by

jax

Updated on June 06, 2022

Comments

  • jax
    jax about 2 years

    I need to access and Android context for a JUnit Test.

    I have tried using MockContext and extending the AndroidTestCase but each time I get an error saying (stub!)