androidx.test.InstrumentationRegistry被弃用了。

68

转换为 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'
6个回答

109

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

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

如果尚未这样做,我认为您还可以使用新的测试依赖项:androidTestImplementation 'androidx.test:core:1.0.0-beta02'


14
这是来自androix.test.platform.app包的InstrumentationRegistry - woprandi
@woprandi的评论解决了我的问题。谢谢! - Shredder
2
我已经添加了“androidx.test:core:1.1.0”,但我无法访问ApplicationProvider。我错过了什么?谢谢。 - lorenzo
@lorenzo,请看我的回答。 - Mark O'Sullivan

54

在使用 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()

6
我真诚地想知道为什么使用AndroidX的Android Studio项目不会自带最新版本的测试部分。 - Dakatine
1
这让我出现了错误:"error: package androidx.test.platform.app does not exist"。 - Phlip
1
这里是我上面关于 import 问题的 解决方案。它与库依赖项的添加方式有关。 - AdamHurwitz
1
@Adam Hurwitz的建议对我很有帮助。非常感谢。 - Ajay
1
@Mark O'Sullivan 这对我来说像魔术一样起作用,谢谢! - ibrhm117
显示剩余3条评论

12

以下代码现在已被弃用:

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

改为使用:

Context context = ApplicationProvider.getApplicationContext();

这会出现“错误:找不到 androidx.test.core.app 包”的提示。 - Phlip
1
请尝试添加以下代码:androidTestImplementation 'androidx.test:core:1.2.0' - Akgun Studio

8

我花了很多时间将依赖项从androidTestImplementation改为testImplementation,反之亦然,在应用程序的build.gradle中。

我的错误在于我将测试类创建在test文件夹中,而不是androidTest文件夹中,因此会出现AndroidJuit4InstrumentationRegistry的无法解析错误。

当我将我的测试文件移动到androidTest文件夹中时,通过在build.gradle中使用androidTestImplementation的依赖项实现测试库,则问题得到解决。


我不知道为什么你没有得到更多的赞。这对我来说是个问题。回想起来很明显,但当初进行Android测试时,并不明显文件夹的重要性。 - The Fox

4
在Kotlin中使用,为了获取Context:
InstrumentationRegistry.getInstrumentation().targetContext

3
请使用以下导入。
import androidx.test.platform.app.InstrumentationRegistry

Kotlin ex
   InstrumentationRegistry.getInstrumentation().context,

导入路径在使用SDK版本30的Java中也是相同的。 - user8128167

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接