Espresso how to test if Activity is finished?

Viewed 19284

I want to assert that my Acitivty that I am currently testing is finished when certain actions are performed. Unfortunately so far I am only to assert it by adding some sleep at the end of the test. Is there a better way ?

import android.content.Context;
import android.os.Build;
import android.support.test.rule.ActivityTestRule;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static org.junit.Assert.assertTrue;

@SuppressWarnings("unchecked")
@RunWith(JUnit4.class)
@LargeTest
public class MyActivityTest {

    Context context;

    @Rule
    public ActivityTestRule<MyActivity> activityRule
            = new ActivityTestRule(MyActivity.class, true, false);

    @Before
    public void setup() {
        super.setup();
        // ...
    }

    @Test
    public void finishAfterSomethingIsPerformed() throws Exception {

        activityRule.launchActivity(MyActivity.createIntent(context));

        doSomeTesting();

        activityRule.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fireEventThatResultsInTheActivityToFinishItself();
            }
        });

        Thread.sleep(2000); // this is needed :(

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            assertTrue(activityRule.getActivity().isDestroyed());
        }

    }

}
7 Answers

Maybe a little late but this is also possible:

assertThat(activityRule.getActivityResult(), hasResultCode(Activity.RESULT_CANCELED));

ActivityTestRule is deprecated now. So, my answer is based on ActivityScenario which is the new alternative for ActivityTestRule.

To test whether the current activity is finished(destroyed) or not. You can simply code like -

Way.1 ActivityScenario.launch(YourActivityName::class.java).use { activityScenario -> //Your test code

  assertTrue(activityScenario.state == Lifecycle.State.DESTROYED)
}
  • activityScenario.state tells the current state of the activity under test
  • Lifecycle.State.DESTROYED tells that the activity is destroyed

Way.2

ActivityScenario<MyActivity> scenario = ActivityScenario.launch(MyActivity.class);
   // Let's say MyActivity has a button that finishes itself.
   onView(withId(R.id.finish_button)).perform(click());
   assertThat(scenario.getResult().getResultCode()).isEqualTo(Activity.RESULT_OK);

If you haven't set a result in your activity, you can just use:

assertTrue(activityRule.scenario.result.resultCode == Activity.RESULT_CANCELED)
Related