I am trying to test a button that start a new activity using only ActivityInstrumentationTestCase2 without Robotium, and it's working fine, but when I try to run the next test case, it's not able to start.
Following what was explained in this question, I was able to continue the test in the next activity and keep performing clicks, but I would like to separate the tests in different functions.
I tried to start a new activity on setup using the following code but it didn't work, I also tried to do the same thing on each function but it didn't work too.
Instrumentation instrumentation = getInstrumentation();
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(AuthenticateActivity.class.getName(), null, false);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(), AuthenticateActivity.class.getName());
instrumentation.startActivitySync(intent);
Activity currentActivity = instrumentation.waitForMonitorWithTimeout(monitor, 5);
How can I start a new activity and keep running the next test functions?
I figured it out.
After some debugs I noticed that the second test was hanging on the startActivitySync() method when I was calling getActivity(), it was happening because I was not finishing the previous started Activity. To finish it, I did the following:
Button button = testActivity.findViewById(R.id.button);
//add the monitor before starting the new activity
Instrumentation.ActivityMonitor monitor = getInstrumentation().addMonitor(StartedActivity.class.getName(), null, false);
//Clicking this button will open the new Activity
TouchUtils.clickView(this, button);
getInstrumentation().waitForIdleSync();
//get the started Activity
StartedActivity startedActivity = (StartedActivity)instrumentation.waitForMonitor(monitor);
//finishing the started activity solved the problem
startedActivity.finish();