0

The intention is: the app starts with a welcome page(corresponding WelcomeActivity) which will last for 2 seconds, then will auto jump to main page(corresponding MainActivity). I want to write a test to cover that but failed...

My test code as below:

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class WelcomeActivityTest {

    @Test
    public void should_navigate_to_main_activity() throws Exception {
        Robolectric.setupActivity(WelcomeActivity.class);
        ShadowApplication instance = ShadowApplication.getInstance();
        Intent nextStartedActivity = instance.getNextStartedActivity();
        assertNotNull(nextStartedActivity);
        String className = nextStartedActivity.getComponent().getClassName();
        assertThat(className, is(LoginActivity.class.getName()));
    }
}

My implementation code as below:

public class WelcomeActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fade, R.anim.hold);
                WelcomeActivity.this.finish();
            }
        }, 2000);
    }
}
EastOcean
  • 1,222
  • 11
  • 10
  • similar problem as http://stackoverflow.com/questions/24642049/android-testing-handler-postdelayed?lq=1 – EastOcean May 24 '16 at 15:41

1 Answers1

2

the key point here is more like how to test handler postDelayed task. As the test you wrote, you could not get the nextStartedActivity because the handler needs 2 more minutes delayed to execute.

Assuming you use the Robolectric 3, and if you want to test handler delayed actions, try below:

@Test
public void should_navigate_to_main_activity() throws Exception {
    Robolectric.setupActivity(WelcomeActivity.class);

    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    ShadowApplication instance = ShadowApplication.getInstance();
    Intent nextStartedActivity = instance.getNextStartedActivity();
    assertNotNull(nextStartedActivity);
    String className = nextStartedActivity.getComponent().getClassName();
    assertThat(className, is(LoginActivity.class.getName()));
}

The ShadowLooper is provided by Robolectric. It will run all delayed tasks when you invoked ShadowLooper.runUiThreadTasksIncludingDelayedTasks().

You could also find the similar question here.

Community
  • 1
  • 1
Ming Gong
  • 46
  • 3