Android Unit Tests Requiring Context

I am writing my first Android database backend and I'm struggling to unit test the creation of my database.

Currently the problem I am encountering is obtaining a valid Context object to pass to my implementation of SQLiteOpenHelper. Is there a way to get a Context object in a class extending TestCase? The solution I have thought of is to instantiate an Activity in the setup method of my TestCase and then assigning the Context of that Activity to a field variable which my test methods can access...but it seems like there should be an easier way.


Solution 1:

You can use InstrumentationRegistry methods to get a Context:

InstrumentationRegistry.getTargetContext() - provides the application Context of the target application.

InstrumentationRegistry.getContext() - provides the Context of this Instrumentation’s package.


For AndroidX use InstrumentationRegistry.getInstrumentation().getTargetContext() or InstrumentationRegistry.getInstrumentation().getContext().

New API for AndroidX: ApplicationProvider.getApplicationContext()

Solution 2:

You might try switching to AndroidTestCase. From looking at the docs, it seems like it should be able to provide you with a valid Context to pass to SQLiteOpenHelper.

Edit: Keep in mind that you probably have to have your tests setup in an "Android Test Project" in Eclipse, since the tests will try to execute on the emulator (or real device).