Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 988
initialxy Avatar asked Jul 27 '12 18:07

initialxy


1 Answers

getInstrumentation().addMonitor(NextActivity.class.getName(), null, true);

Did the trick. Notice that the last parameter is a flag that indicates whether or not to block the activity from launching. Setting it to true solved the problem.

link to doc

like image 186
initialxy Avatar answered Sep 27 '22 18:09

initialxy