Espresso - How can I check if an activity is launched after performing a certain action?

Solution 1:

You can use:

intended(hasComponent(YourExpectedActivity.class.getName()));

Requires this gradle entry:

androidTestCompile ("com.android.support.test.espresso:espresso-intents:$espressoVersion")

The import for the intended() and hasComponent()

import static android.support.test.espresso.intent.Intents.intended;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;

as mentioned by Shubam Gupta please remember to call Intents.init() before calling intended(). You can eventually call it in the @Before method.

Solution 2:

Try:

intended(hasComponent(YourActivity.class.getName()));

Also, keep in mind

java.lang.NullPointerException is thrown if Intents.init() is not called before intended()

Solution 3:

You may do it as follows:

    @Test
public void testLoginAttempt() {
    Espresso.onView(ViewMatchers.withId(R.id.username)).perform(ViewActions.clearText()).perform(ViewActions.typeText("[email protected]"));
    Espresso.onView(ViewMatchers.withId(R.id.username)).perform(ViewActions.clearText()).perform(ViewActions.typeText("invalidpassword"));

    Intents.init();
    Espresso.onView(ViewMatchers.withId(R.id.login_button)).perform(ViewActions.click());
    Intents.release();
}

java.lang.NullPointerException is thrown if Intents.init() is not called.