I have a test suite for an android application, testing multiple scenarios. For most of them it makes sense to use AndroidX test framework's launchActivity.
I also have, in the same suite, tests that tests the recovery of activities from a bundle. These tests require `"Don't keep activities" in the developer options to be enabled, since only then it is straightforward to have a setup such that onCreate is being called with a non-null savedInstanceState.
However, when Don't keep activities
in the developer options is enabled, launchActivity fails with an IllegalStateException
with the following stack trace:
java.lang.IllegalStateException: "Don't keep activities" developer options must be disabled for ActivityScenario
at androidx.test.internal.util.Checks.checkState(Checks.java:96)
at androidx.test.core.app.ActivityScenario.launchInternal(ActivityScenario.java:218)
at androidx.test.core.app.ActivityScenario.launch(ActivityScenario.java:190)
[...]
I am wondering why this is limitation exists and how to deal with? Since it prevents testing scenarios when the activity is restored from instance state.
Even if UiAutomator is used for these specific test cases testing recovery of an activity from instance state, the tests cant really run together on the same device/emulator, since this setting is a system setting.
Alternatively, one could switch the setting on and off before and after the tests, however this only works either on a root device, or one would need to use UiAutomator to flip the system setting switch, which is very slow.
It turns out that ActivityScenario's recreate covers this specific scenario:
A current Activity will be destroyed after its data is saved into Bundle with onSaveInstanceState(Bundle), then it creates a new Activity with the saved Bundle. After this method call, it is ensured that the Activity state goes back to the same state as its previous state.