不推荐使用androidx.test.InstrumentationRegistry

Mor*_*zov 34 android deprecated androidx

切换到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'
Run Code Online (Sandbox Code Playgroud)

小智 45

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

如果您需要应用程序,您可以使用 androidx.test.platform.app.InstrumentationRegistry

如果你还没有,我想你也是一个新的测试依赖: ApplicationProvider.getApplicationContext<MyAppClass>()

  • 它是来自`androix.test.platform.app`包的`InstrumentationRegistry` (9认同)
  • 我添加了“androidx.test:core:1.1.0”,但我无权访问 ApplicationProvider。我想念什么?谢谢 (2认同)

Mar*_*van 34

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

androidTestImplementation 'androidx.test:core:1.1.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
Run Code Online (Sandbox Code Playgroud)

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

确保导入这两个.

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
Run Code Online (Sandbox Code Playgroud)

现在,val context = InstrumentationRegistry.getContext()您可以使用下面显示的行代替使用

val context = InstrumentationRegistry.getInstrumentation().getTargetContext()
Run Code Online (Sandbox Code Playgroud)

  • 我真诚地想知道为什么使用androidx的android studio项目不会随测试部分一起更新。 (3认同)

小智 9

以下代码现已弃用:

Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
Run Code Online (Sandbox Code Playgroud)

而是使用:

Context context = ApplicationProvider.getApplicationContext();
Run Code Online (Sandbox Code Playgroud)


Aja*_*jay 7

我花了很多时间在 app 中使用testImplementation而不是androidTestImplementation反向移动依赖项build.gradle

我的错是,我创建了测试类test文件夹而不是androidTest文件夹,以便让悬而未决的错误AndroidJuit4InstrumentationRegistry

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