我正在测试一个在其 onCreate()
期间启动另一个 Activity 的 Activity 。第二个 Activity 由 startActivityForResult()
启动,然后主 Activity 等待 onActivityResult()
。
我正在尝试使用 Espresso 对此进行测试,尝试使用 intending()
对第二个 Activity 进行 stub ,并使用 intended()
验证它是否发生。
尽管 espresso-intents 似乎并非设计用于处理从 onCreate()
方法 ( see the warning in the last paragraphs here ) 中启动的 Intent 。
有没有人设法对从 onCreate()
中启动的 Intent 进行 stub ,如果是,怎么做?
最佳答案
通过使用以下 Kotlin 代码,我能够为自己工作:
@Rule @JvmField
val activityRule: IntentsTestRule<MainActivity> =
object : IntentsTestRule<MainActivity>(MainActivity::class.java, true, false) {
override fun beforeActivityLaunched() {
super.beforeActivityLaunched()
Intents.init()
intending(hasComponent(LaunchedFromOnCreateActivity::class.java.name)).respondWith(Instrumentation.ActivityResult(RESULT_OK, null))
}
override fun afterActivityLaunched() {
Intents.release()
super.afterActivityLaunched()
}
}
一般的想法是,由于生命周期的事情发生在 beforeActivityLaunched 和 afterActivityLaunched 之间,您需要在那里设置您的intending。也就是说,这无法进行预期的测试。
关于java - 使用 Espresso stub 在测试 Activity 的 onCreate 期间启动的 Intents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42888290/