Android Unit Tests Requiring Context

DatabaseAndroidUnit Testing

Database Problem Overview


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.

Database Solutions


Solution 1 - Database

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 - Database

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

Solution 3 - Database

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

Solution 4 - Database

Using the AndroidTestCase:getContext() method only gives a stub Context in my experience. For my tests, I'm using an empty activity in my main app and getting the Context via that. Am also extending the test suite class with the ActivityInstrumentationTestCase2 class. Seems to work for me.

public class DatabaseTest extends ActivityInstrumentationTestCase2<EmptyActivity>
    EmptyActivity activity;
    Context mContext = null;
    ...
    @Before
    public void setUp() {
		activity = getActivity();
		mContext = activity;
	}
	... //tests to follow
}

What does everyone else do?

Solution 5 - Database

You can derive from MockContext and return for example a MockResources on getResources(), a valid ContentResolver on getContentResolver(), etc. That allows, with some pain, some unit tests.

The alternative is to run for example Robolectric which simulates a whole Android OS. Those would be for system tests: It's a lot slower to run.

Solution 6 - Database

You should use ApplicationTestCase or ServiceTestCase.

Solution 7 - Database

Extending AndroidTestCase and calling AndroidTestCase:getContext() has worked fine for me to get Context for and use it with an SQLiteDatabase.

The only niggle is that the database it creates and/or uses will be the same as the one used by the production application so you will probably want to use a different filename for both

eg.

  public static final String    NOTES_DB      = "notestore.db";
  public  static final String   DEBUG_NOTES_DB = "DEBUG_notestore.db";

Solution 8 - Database

First Create Test Class under (androidTest).

Now use following code:

public class YourDBTest extends InstrumentationTestCase {

private DBContracts.DatabaseHelper db;
private RenamingDelegatingContext context;

@Override
public void setUp() throws Exception {
    super.setUp();
    context = new RenamingDelegatingContext(getInstrumentation().getTargetContext(), "test_");
    db = new DBContracts.DatabaseHelper(context);
}

@Override
public void tearDown() throws Exception {
    db.close();
    super.tearDown();
}

@Test
public void test1() throws Exception {
	// here is your context
	context = context;
}}

Solution 9 - Database

Initialize context like this in your Test File

private val context = mock(Context::class.java)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMacy AbbeyView Question on Stackoverflow
Solution 1 - DatabaseamukhachovView Answer on Stackoverflow
Solution 2 - DatabaseErich DouglassView Answer on Stackoverflow
Solution 3 - DatabaseEhsanView Answer on Stackoverflow
Solution 4 - DatabaseTim KistView Answer on Stackoverflow
Solution 5 - DatabaseWernightView Answer on Stackoverflow
Solution 6 - DatabaseNeilView Answer on Stackoverflow
Solution 7 - DatabaseIanView Answer on Stackoverflow
Solution 8 - DatabaselidoxView Answer on Stackoverflow
Solution 9 - DatabasewhoisasheeshView Answer on Stackoverflow