androidx.test.InstrumentationRegistry 已弃用

androidx.test.InstrumentationRegistry is deprecated

切换到 AndroidX 并已弃用:import androidx.test.InstrumentationRegistry

如果我进行下一次导入:import androidx.test.platform.app.InstrumentationRegistry 我不能使用 getContext()

例如: val context = InstrumentationRegistry.getContext().

build.gradle中:

androidTestImplementation 'androidx.test.ext:junit:1.0.0-beta02'
androidTestImplementation 'androidx.test:runner:1.1.0-beta02'

您可以在大多数情况下使用 InstrumentationRegistry.getInstrumentation().getTargetContext() androidx.test.platform.app.InstrumentationRegistry

如果需要应用程序,可以使用ApplicationProvider.getApplicationContext<MyAppClass>()

如果你还没有,我想你也可以使用新的测试依赖: androidTestImplementation 'androidx.test:core:1.0.0-beta02'.

当您使用 Android X 时,您需要确保应用的 build.gradle 文件中包含以下内容

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

第二个是确保您在测试中使用正确的 AndroidJUnit4。

确保导入这两个文件。

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

现在您可以使用下面显示的行

而不是使用 val context = InstrumentationRegistry.getContext()
val context = InstrumentationRegistry.getInstrumentation().getTargetContext()

对于Kotlin的使用,为了获取上下文:

InstrumentationRegistry.getInstrumentation().targetContext

以下代码现已弃用:

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

改为使用:

Context context = ApplicationProvider.getApplicationContext();

我花了很多时间在应用 build.gradle.

中使用 testImplementation 而不是 androidTestImplementation 移动依赖项并反向移动

我的错误是我在 test 文件夹而不是 androidTest 文件夹中创建了测试 class,因此出现 AndroidJuit4 和 [=16= 未解决的错误].

当我将我的测试文件转移到 androidTest 文件夹时,问题已通过在 build.gradle.

中使用 androidTestImplementation 的测试库的依赖实现解决了

使用下面的导入

import androidx.test.platform.app.InstrumentationRegistry

Kotlin ex
   InstrumentationRegistry.getInstrumentation().context,