Check if a new Activity is started with Espresso by click on view

Issue

I have a button when click on this, start activity A.

 startActivityForResult(Intent(this, A::class.java)

I need to check in an esspresso test when click on the button, start activity A or not?

onView(withId(R.id.button))
       .check(matches(isDisplayed()))
       .check(matches(isEnabled()))
       .perform(click())

        // check is this A Activity start or not?

Solution

You can use espresso-intents package.

First, try to add the latest version into your build.gradle:

   androidTestImplementation "androidx.test.espresso:espresso-intents:3.1.1"

Then, use IntentsTestRule to check whether your intent is started or not:

    @get:Rule
    val intentRule  IntentsTestRule(MainActivity::class.java)

    @Test
    fun verify_FakeActivity_is_started() {
        onView(withId(R.id.button))
            .check(matches(isDisplayed()))
            .check(matches(isEnabled()))
            .perform(click())

        intended(hasComponent(FakeActivity::class.java.name))
    }

Answered By – Saeed Masoumi

Leave a Comment