Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso how to test if Activity is finished?

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());         }      }  } 
like image 572
JoachimR Avatar asked Mar 08 '16 09:03

JoachimR


People also ask

How do you test activity?

To test an activity, you use the ActivityTestRule class provided by the Android Testing Support Library. This rule provides functional testing of a single activity. The activity under test will be launched before each test annotated with @Test and before any method annotated with @Before.

How do you check Espresso visibility?

One simple way to check for a View or its subclass like a Button is to use method getVisibility from View class. I must caution that visibility attribute is not clearly defined in the GUI world. A view may be considered visible but may be overlapped with another view, for one example, making it hidden.


1 Answers

In my case I can test for isFinishing():

assertTrue(activityTestRule.getActivity().isFinishing());

instead of:

    Thread.sleep(2000); // this is needed :(      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {         assertTrue(activityRule.getActivity().isDestroyed());     } 

Another advantage of isFinishing() is, that you do not need the Version check.

like image 171
keineantwort Avatar answered Oct 11 '22 19:10

keineantwort