Search code examples
androidjunit4android-contextandroid-libraryandroid-testing

library test: how to create a Context?


Android library test: how to create a Context? e.g.

src/main/java
src/androidTest/java

The android lib (main source set) uses android sqlite database, but does not have any Activities. The SQLiteOpenHelper needs a Context to create.

class MySQLiteOpenHelper extends SQLiteOpenHelper {
    MySQLiteOpenHelper(Context context, String database, int version) {
        super(context, database, null, version);
    }
}

How to create a Context for testing? How to pass the Context to junit tests under androidTest ? e.g.

@Runner(Parameterized.class)
public class FooTest {
    @Test
    public void testFoo() {
        // how to get a Context instance?
        MySQLiteOpenHelper helper = new MySQLiteOpenHelper(context, "test.db", 1);
        ...
    }
}

Solution

  • How to create a Context for testing?

    Call InstrumentationRegistry.getTargetContext() to get a Context for the app or module being tested.