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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With