title: Espresso how to test if Activity is finished?
body: <p>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 ?</p>
  
  <pre><code>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&lt;MyActivity&gt; 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 &gt;= Build.VERSION_CODES.JELLY_BEAN_MR1) {
              assertTrue(activityRule.getActivity().isDestroyed());
          }
  
      }
  
  }
  </code></pre>