切换到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'
在大多数情况下,您可以在androidx.test.platform.app.InstrumentationRegistry
中使用InstrumentationRegistry.getInstrumentation().getTargetContext()
。
如果您需要该应用程序,您可以使用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()
以下代码现在已弃用:
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
请改用:
Context context = ApplicationProvider.getApplicationContext();
我花了很多时间在应用程序build.gradle
中使用testImplementation
而不是androidTestImplementation
和reverse来移动依赖项。
我的错误是我在test
文件夹而不是androidTest
文件夹中创建了测试类,因此得到了AndroidJuit4
和InstrumentationRegistry
的未解决的错误。
当我将我的测试文件转移到androidTest
文件夹中,然后在build.gradle
中使用androidTestImplementation
独立实现测试库的问题得到了解决。