Unit Testing a Android Activity which contains a Runnable

In order to unit test an Android Activity to verify that the Runnable is called you need to add a call to waitForIdle to the Instrumentation, which is called when all Runnables have been executed.

Here is the activity that we are testing:

public class SplashScreenActivity extends Activity {

public final int SPLASH_DISPLAY_LENGTH = 1200;
 
   @Override
   public void onCreate(Bundle icicle) {
 super.onCreate(icicle);
 setContentView(R.layout.splash);

 new Handler().postDelayed(new Runnable() {

  public void run() {    
   Intent mainIntent = new Intent(SplashScreenActivity.this, NextActivity.class);
   startActivity(mainIntent);
   finish();
  }

 }, SPLASH_DISPLAY_LENGTH);
   }
}

Here is the method in the Unit Test Class:

public void testSubLaunch() {
        SplashScreenActivity mActivity = startActivity(new Intent(), null, null);
        getInstrumentation().waitForIdle(new Runnable() {
  public void run() {
   assertNotNull(getStartedActivityIntent());
   assertTrue(isFinishCalled());
  }         
        });    
    }