How to recreate an activity in instrumented tests without non-configuration instance being saved?

Viewed 61

So here is the deal. I know about ActivityScenario.recreateActivity(). It perfectly reproduces the configuration change case, when all the non-configuration instance from onRetainNonConfigurationInstance() (say ViewModelStore) is passed into the new activity.

But how would one test the case when the activity is fully destroyed and recreated just from the savedInstanceState bundle? I want ViewModelStore to be erased, and ideally, savedInstanceState Bundle to be parceled/unparceled. Similar to when the "Don't keep activities" flag is enabled in Developer options or when the whole process is killed/recreated.

I've looked around but really stuck with this at the moment.

1 Answers

So far, I've created a workaround for the desired behaviour, but I'm still looking for a proper solution.

What I've done in the meantime, is that I'm just manually clearing an activity's ViewModelStore when the activity is destroyed:

UiThreadStatement.runOnUiThread {
    scenario.onActivity { 
        it.lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                (owner as ComponentActivity).viewModelStore.clear()
            }
        })
    }
}
scenario.recreate()

This simulates the full activity recreation and is enough for testing purposes.

Related