Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Espresso to stub Intents started during the onCreate of the tested activity

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?

like image 804
Ken Cooper Avatar asked Mar 19 '17 15:03

Ken Cooper


People also ask

What is intent testing in Android?

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.


1 Answers

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.

like image 108
Calvin Avatar answered Oct 13 '22 03:10

Calvin