20

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.

Danilo Bargen
  • 18,626
  • 15
  • 91
  • 127
  • What exactly doesn't seem to work properly? – yorkw Apr 24 '12 at 11:18
  • What do you mean when you say, "doing it manually?" – Joel Skrepnek Apr 24 '12 at 12:58
  • @JoelSkrepnek There is a checkbox that enables and disables the feature. When I uncheck the checkbox and close and reopen the app, all data is gone. When I check it and close or kill and then reopen the app, all form data is restored. – Danilo Bargen Apr 24 '12 at 13:02

6 Answers6

14

By calling (or trigger a screen orientation change):

activity.finish(); // old activity instance is destroyed and shut down.
activity = getActivity(); // new activity instance is launched and created.

Causing the activity go through the complete recreation life cycle:

onPause() -> onStop() -> onDestroy() -> onCreate()

What you need is:

onPause() -> onStop() -> onRestart()

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:

MyActivity myActivity = getActivity();
// make activity falling into restart phase:
getInstrumentation().callActivityOnRestart(myActivity);

Activity life cycle diagram quoting from official dev guide: enter image description here

yorkw
  • 40,926
  • 10
  • 117
  • 130
  • 1
    Actually, I already did give the first solution a try, and it did not seem to work as you can see in my question. But maybe you're right and the problem is unrelated... Re your second suggestion, I'll try that one later on... – Danilo Bargen Apr 25 '12 at 10:58
  • that actually did it, thanks very much! :) would you mind putting this in the top of your answer for others to find more easily? – Danilo Bargen May 04 '12 at 08:40
  • Thanks for the edit. One last remark: I also ran into synchronization problems. The test didn't wait for my lifecycle eventhandler to finish. Adding `getInstrumentation().waitForIdleSync()` after restarting the activity helped. – Danilo Bargen May 04 '12 at 09:18
  • Does getInstrumentation().callActivityOnRestart(myActivity) really results into onPause() -> onStop() -> onRestart()? I tried and it is not. – Eugene Feb 12 '13 at 11:19
  • @siik, it is hard to tell without more details and investigation. My first shot is make sure callActivityOnRestart() is called off the application's main thread (or UI thread), i.e. in case if using `@UiThreadTest` annotation wrap the whole test method body. – yorkw Feb 12 '13 at 22:08
10

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+):

    getInstrumentation().runOnMainSync(new Runnable() {
        @Override
        public void run() {
            activity.recreate();
        }
    });
    setActivity(null);
    activity = getActivity();

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.

ZoFreX
  • 8,812
  • 5
  • 31
  • 51
2

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.

Joel Skrepnek
  • 1,651
  • 1
  • 13
  • 21
  • Interesting idea. The problem with this is that Android saves form data by default when doing a screen orientation change, so that doesn't really cover this test case... – Danilo Bargen Apr 24 '12 at 12:42
  • 1
    A screen orientation change resulting complete Activity life cycle: ... -> onPause() -> onStop() -> onDestroy() -> onCreate() -> onStart() -> ..., which has the same behavior of calling activity.finish(); activity = getActivity(); – yorkw Apr 24 '12 at 12:49
  • @DaniloBargen I don't believe form data is saved by default when an activity is destroyed. – Joel Skrepnek Apr 24 '12 at 12:54
  • @JoelSkrepnek I tested it on my ICS device. killing or closing the app results in an empty form field. When changing the screen orientation, all form data is retained. – Danilo Bargen Apr 24 '12 at 13:01
0

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...

Thkru
  • 4,218
  • 2
  • 18
  • 37
0

Change your code as follows:

mActivity.finish();
    setActivity(null);
    mActivity = this.getActivity();

A full explanation can be found in this question

Community
  • 1
  • 1
Padi
  • 291
  • 3
  • 4
0

ActivityScenario.recreate() seems to work fine. I don't think the other complex solutions are needed anymore.

Given this test

@Test
fun activity_is_recreated() {
  activityScenario = ActivityScenario.launch(TestingLifecycleActivity::class.java)

  activityScenario.onActivity {
      Timber.d("inside onActivity $it")        
      //do assertions   
  }

  Timber.d("pre recreate")
  activityScenario.recreate()
  Timber.d("post recreate")

  activityScenario.onActivity {
      Timber.d("inside onActivity $it")
      //do assertions
  }
}

These are the lifecycle related logs

Lifecycle status change: TestingLifecycleActivity@e34cfb7 in: PRE_ON_CREATE
Lifecycle status change: TestingLifecycleActivity@e34cfb7 in: CREATED
Lifecycle status change: TestingLifecycleActivity@e34cfb7 in: STARTED
Lifecycle status change: TestingLifecycleActivity@e34cfb7 in: RESUMED
inside onActivity TestingLifecycleActivity@e34cfb7
pre recreate
Schedule relaunch activity: TestingLifecycleActivity
Lifecycle status change: TestingLifecycleActivity@e34cfb7 in: PAUSED
Lifecycle status change: TestingLifecycleActivity@e34cfb7 in: STOPPED
Lifecycle status change: TestingLifecycleActivity@e34cfb7 in: DESTROYED

//new activity instance is launched
Lifecycle status change: TestingLifecycleActivity@ac46813 in: PRE_ON_CREATE
Lifecycle status change: TestingLifecycleActivity@ac46813 in: CREATED
Lifecycle status change: TestingLifecycleActivity@ac46813 in: STARTED
Lifecycle status change: TestingLifecycleActivity@ac46813 in: RESUMED
post recreate
inside onActivity TestingLifecycleActivity@ac46813
Finishing activity: TestingLifecycleActivity@ac46813
Maragues
  • 37,861
  • 14
  • 95
  • 96