Dominic Fuchs Dominic Fuchs - 3 months ago 52x
Android Question

Android JUnit4 Testing - Where to get Context from?

I have to build an app with sqlite usage. Now I want to write my unit tests. This unit Tests should test my class SQLiteBridge. SQLiteBridge provides DAOs for every child class of Model.

Now I got the problem that I need a context to create my SQLiteBridge. SQLiteBridge creates and handles a sqlite database on the system..

Where to get the Context-Object from?

My setup is like here (so I'm using Junit4 [thanks god]):

EDIT: I hope there is a way like the old AndroidTestCase to extend but not loosing Junit4. :)


As described here: Use the InstrumentationRegistry to obtain the context.

However if you call InstrumentationRegistry.getContext() directly you may get an exception opening your database. I believe this is because the context returned by getContext() points to the instrumentation's context rather than that of your application / unit test. Instead use InstrumentationRegistry.getInstrumentation().getTargetContext()

For example:

public class SqliteTest {

    Context mMockContext;

    public void setUp() {
        mMockContext = new RenamingDelegatingContext(InstrumentationRegistry.getTargetContext(), "test_");

The RenamingDelegatingContext simply prefixes the file/database names with test_ to prevent you from overwriting data that you may have in the same simulator.