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?
Intents enables validation and stubbing of intents sent out by the application under test. An example test that simply validates an outgoing intent: public void testValidateIntentSentToPackage() { // User action that results in an external "phone" activity being launched.
I was able to get this working for myself by using the following Kotlin code:
@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()
}
}
The general idea is that since the lifecycle stuff happens in between beforeActivityLaunched and afterActivityLaunched, you'll need to set up your intending there. That said, this doesn't make it possible to do intended testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With