Android unit test with ActivityInstrumentationTestCase2, getActivity() hangs when previous test case causes another Activity to be launched

Viewed 3680

I'm trying to run multiple test cases for a login Activity using ActivityInstrumentationTestCase2. The first test case tests login successful, which causes the Activity to launch the next Activity by calling startActivity(Intent intent). Now there's another Activity on top of the Activity I'm trying to test. The first test case passes, and the second test case is started. However it will forever hangs at getActivity() when it is being called by the second test case.

If I go into my login Activity's code and comment out the part that calls startActivity(Intent intent), then both test cases will run successfully.

I've already tried a few things. I used Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity stack. In which case, the top activity is closed, and login Activity is revealed, but it still gets stuck at getActivity() when second test case is started.

I also tried to sendKeys(KeyEvent.KEYCODE_BACK), but that has no effects.

What can I do to overcome this? Thanks!

2 Answers

In my case I just close activity after each case:

public void tearDown() {
    // here goes other code to be executed after each test case
    getActivity().finish();
}
Related