Get context of test project in Android junit test case

There's new approach with Android Testing Support Library (currently androidx.test:runner:1.1.1). Kotlin updated example:

class ExampleInstrumentedTest {

    lateinit var instrumentationContext: Context

    @Before
    fun setup() {
        instrumentationContext = InstrumentationRegistry.getInstrumentation().context
    }

    @Test
    fun someTest() {
        TODO()
    }
}

If you want also app context run:

InstrumentationRegistry.getInstrumentation().targetContext

Full running example: https://github.com/fada21/AndroidTestContextExample

Look here: What's the difference between getTargetContext() and getContext (on InstrumentationRegistry)?


After some research the only working solution seems to be the one yorkw pointed out already. You'd have to extend InstrumentationTestCase and then you can access your test application's context using getInstrumentation().getContext() - here is a brief code snippet using the above suggestions:

public class PrintoutPullParserTest extends InstrumentationTestCase {

    public void testParsing() throws Exception {
        PrintoutPullParser parser = new PrintoutPullParser();
        parser.parse(getInstrumentation().getContext().getResources().getXml(R.xml.printer_configuration));
    }
}

Tags:

Junit

Android