Ken*_*per 5 java testing android android-activity android-espresso
I am testing an activity that starts another activity during its onCreate(). This second activity is started with startActivityForResult(), and the main activity then waits for onActivityResult().
I'm trying to use Espresso to test this, attempting to stub the second activity with intending(), and verify it occurred using intended().
It appears though that espresso-intents isn't designed to work with intents launched from within the onCreate() method (see the warning in the last paragraphs here).
Has anyone managed to stub an Intent started from within onCreate(), and if so, how?
通过使用以下 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()
}
}
Run Code Online (Sandbox Code Playgroud)
一般的想法是,由于生命周期的事情发生在 beforeActivityLaunched 和 afterActivityLaunched 之间,你需要在那里设置你的意图。也就是说,这无法进行预期的测试。
| 归档时间: |
|
| 查看次数: |
808 次 |
| 最近记录: |