Which is a better way to access Context in instrumented unit tests?

363 Views Asked by At

Which of the following is more recommended to access Context in instrumented unit tests: using ApplicationProvider or InstrumentationRegistry?

val context: Context = ApplicationProvider.getApplicationContext()
import androidx.test.platform.app.InstrumentationRegistry

val context: Context = InstrumentationRegistry.getInstrumentation().targetContext

I know androidx.test.InstrumentationRegistry is deprecated, but androidx.test.platform.app.InstrumentationRegistry is not.

1

There are 1 best solutions below

0
On

You can either use androidx.test.platform.app.InstrumentationRegistry or android.support.test.InstrumentationRegistry, according to your respective Android SDK version, and get the Context by:

Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();