Skip to content Skip to sidebar Skip to footer

How Do You Get Hold Of An Android Context For A Junit Test From A Java Project?

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!)

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 extendingAndroidTestCase 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)@SmallTestpublicclassConnectivityTest {

    @Rulepublic ActivityTestRule<MainActivity> mActivityRule = newActivityTestRule<>(MainActivity.class);

    @TestpublicvoidtestIsConnected()throws Exception {
        Contextcontext= mActivityRule.getActivity().getBaseContext();
        ConnectivityManagercm= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        booleanconnected= 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

ContextappContext= InstrumentationRegistry.getTargetContext();

The dependency is:

androidTestCompile 'com.android.support.test:runner:0.5'

Solution 4:

Try this for case when your test class extends ActivityInstrumentationTestCase2:

InputStream is = null;
try {
    is = getInstrumentation().getContext().getAssets().open("your.file");
} catch (IOException e) {
    Log.d("Error", "Error during file opening!!!");
}

Solution 5:

Each Activity is a subclass of Context, so you must use your Activities when you need Context. The class Context is not something you instantiate from an application.

Post a Comment for "How Do You Get Hold Of An Android Context For A Junit Test From A Java Project?"