Android Unit Tests Requiring Context Android Unit Tests Requiring Context database database

Android Unit Tests Requiring Context


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


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


Your test is not a Unit test!!!

When you need

  • Context
  • Read or Write on storage
  • Access Network
  • Or change any config to test your function

You are not writing a unit test.

You need to write your test in androidTest package