How to test saving and restoring state of an android activity with Espresso?

前端 未结 3 688
轻奢々
轻奢々 2021-02-09 09:04

Is there a way of testing the save and restore state code of an activity programmatically ? I mean doing this :

How to test code built to save/restore Lifecycle of an A

3条回答
  •  长情又很酷
    2021-02-09 09:45

    The solution is to use the activity.recreate() method BUT do not forget to follow this by an assertion which waits for an idle state. My problem with my first attempt was that the test I was writing was like :

    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            activity.recreate();
        }
    });
    assertThat(activityTestRule.getActivity().getXXX()).isNull();
    

    Where XXX was a field that I expected to be null when no save/restore state handling had been implemented. But that was not the case because my assertion was not waiting for the recreation task to be completed.

    So in my situation, my problem was solved when I simply add an espresso assertion which does the job, for example by verifiying that the TextView which displayed the XXX field was empty.

    Finally, thanks to the UI thread synchronization provided by Espresso, my test which can assert on my activity save/restore state missing implementation can be written like :

    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            activity.recreate();
        }
    });
    onView(withText("a string depending on XXX value")).check(doesNotExist());
    

    Note that the rotation solution suggested does the job either, but can be much slower than activity.recreate() when we just want to test the activity lifecycle. And in my case it was not relevant since my activity was not implemented for a landscape orientation.

提交回复
热议问题