I'm trying to write an Android activity instrumentation test that stops (onPause()
, then onStop()
) and restarts the current activity. I tried
activity.finish();
activity = getActivity();
...but that doesn't seem to work properly.
The goal of the test is to assert that form data is stored during the onPause()
method and re-read during the onStart()
method. It works when doing it manually, but the test fails, from which I draw the conclusion that activity.finish()
seems to be the wrong way to stop and restart an activity.
Edit: My main problem seems to have been a synchronization issue. After restarting the activity, the test runner didn't wait for all event handlers to finish. The following line halts the test execution until the activity is idle:
getInstrumentation().waitForIdleSync()
Besides that, take a look at the accepted answer for more valuable information about the lifecycle.
Change your code as follows:
A full explanation can be found in this question
By calling (or trigger a screen orientation change):
Causing the activity go through the complete recreation life cycle:
What you need is:
I exposed the Instrumentation API recently and found plenty of interesting activity life cycle trigger method callActivityOnXXX(), the following single line of code should do the tricky:
Activity life cycle diagram quoting from official dev guide:
I tried calling .finish(), setActivity(null), getActivity() and it does restart the activity, but for me it was not restoring the state. I tried out all the other answers on SO, and every other method to do this I could find online, and none of them worked for me. After much experimentation I found the following works (nb: requires API level 11+):
When I do this a new Activity instance is created, and a new instance of the fragment I had attached to the activity earlier in the test is also created, and both the activity and fragment restore their state in the expected manner.
I don't know how this works or why this works, I reached this solution through trial and error, and I have only tested it on a Nexus 4 running KitKat. I can't guarantee it correctly simulates an activity recreation, but it worked for my purposes.
Edit: At a later date I figured out how this works. getActivity() works through registering hooks that receive new Activities being created, which catch the new Activity created by activity.recreate().
setActivity(null)
was required to clear the internal cache backing getActivity, otherwise it will return the old one and not look for a new one.You can see how this works from examining the source code for the various test case classes one extends from.
Maybe u could try to save the name of your activity, finish it... and use reflection to get a new instance of the .class for the new intent to create...
A good way to test lifecycle events is through screen orientation changes. In my experience it's a convenient way to bombproof the onPause / onStart pattern.