Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

androidx.test.InstrumentationRegistry is deprecated

Switched to AndroidX and received deprecated: import androidx.test.InstrumentationRegistry.

If I made next import: import androidx.test.platform.app.InstrumentationRegistry I can't use getContext().

Ex: val context = InstrumentationRegistry.getContext().

In build.gradle:

androidTestImplementation 'androidx.test.ext:junit:1.0.0-beta02' androidTestImplementation 'androidx.test:runner:1.1.0-beta02' 
like image 346
Morozov Avatar asked Oct 22 '18 07:10

Morozov


People also ask

What is InstrumentationRegistry?

public final class InstrumentationRegistry. An exposed registry instance that holds a reference to the instrumentation running in the process and its arguments.

What is AndroidX test?

AndroidX Test is a collection of Jetpack libraries that lets you run tests against Android apps. It also provides a series of tools to help you write these tests. For example, AndroidX Test provides JUnit4 rules to start activities and interact with them in JUnit4 tests.


2 Answers

You can use InstrumentationRegistry.getInstrumentation().getTargetContext() in the most cases from androidx.test.platform.app.InstrumentationRegistry.

If you need the Application, you can use ApplicationProvider.getApplicationContext<MyAppClass>().

If you haven't already, I think you can also use the new test dependency: androidTestImplementation 'androidx.test:core:1.0.0-beta02'.

like image 99
karuto Avatar answered Sep 21 '22 06:09

karuto


When you're using Android X you need to make sure you have the following in your app's build.gradle file

androidTestImplementation 'androidx.test:core:1.1.0' androidTestImplementation 'androidx.test.ext:junit:1.1.0' 

The second one is to make sure you have the correct AndroidJUnit4 to use in your tests.

Make sure you import both of these.

import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 

Now instead of using val context = InstrumentationRegistry.getContext() you can use the line shown below

val context = InstrumentationRegistry.getInstrumentation().getTargetContext() 
like image 41
Mark O'Sullivan Avatar answered Sep 21 '22 06:09

Mark O'Sullivan