不推荐使用androidx.test.InstrumentationRegistry

问题描述 投票:12回答:3

切换到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'
android deprecated androidx
3个回答
19
投票

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

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

如果你还没有,我想你也是一个新的测试依赖:androidTestImplementation 'androidx.test:core:1.0.0-beta02'


30
投票

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

2
投票

对于Kotlin的使用,为了获得Context:

InstrumentationRegistry.getInstrumentation().targetContext

1
投票

InstrumentationRegistry.getInstrumentation().targetContext现在弃用了。使用ApplicationProvider.getApplicationContext();

© www.soinside.com 2019 - 2024. All rights reserved.