jax
jax

Reputation: 38653

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

Upvotes: 14

Views: 18008

Answers (5)

Guillaume Perrot
Guillaume Perrot

Reputation: 4308

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'

Upvotes: 2

Kuba Spatny
Kuba Spatny

Reputation: 27000

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));
    }
}

Upvotes: 5

Alex Sarapin
Alex Sarapin

Reputation: 89

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!!!");
}

Upvotes: 0

Fred Medlin
Fred Medlin

Reputation: 860

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

Upvotes: 23

ognian
ognian

Reputation: 11541

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.

Upvotes: -1

Related Questions