Android ActivityTestRule.getActivity在Before方法中返回null
我需要在每次测试之前清空用户的数据Android ActivityTestRule.getActivity在Before方法中返回null,android,testing,android-espresso,kotlin,Android,Testing,Android Espresso,Kotlin,我需要在每次测试之前清空用户的数据 // Kotlin code fun getActivity() = activityRule.getActivity() Before fun setUp() { cleanUp(getActivity()) } 为此,我需要获取上下文,但在安装程序中,activityRule.getActivity()返回null 我还尝试: Before fun setUp() { val i = Intent() i.addFlags(In
// Kotlin code
fun getActivity() = activityRule.getActivity()
Before
fun setUp() {
cleanUp(getActivity())
}
为此,我需要获取上下文,但在安装程序中,activityRule.getActivity()返回null
我还尝试:
Before
fun setUp() {
val i = Intent()
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
activityRule.lauchActivity(i)
cleanUp(getActivity())
}
我参加了一个活动,但清理工作只有一半的时间有效(我相信一些比赛条件适用于这里)
我希望避免在After函数中进行清理,以便在需要时手动查看我的应用程序状态
在Before函数中是否有上下文
谢谢您可以从
InstrumentationRegistry
获取生产应用程序上下文,如下所示:
InstrumentationRegistry.getTargetContext()
请记住:
InstrumentationRegistry.getContext()
是测试apk的上下文。在撰写本文时,不推荐使用InstrumentationRegistry
。
我使用androidx.test
库中的ApplicationProvider.getApplicationContext()
依赖项是:androidTestImplementation“androidx.test.espresso:espresso核心:3.1.1”
androidx.test.InstrumentationRegistry已弃用。使用androidx.test.platform.app.InstrumentationRegistry。