ActivityScenario is a replacement of ActivityController in Robolectric and ActivityTestRule in ATSL.
When refactoring from ATSL to Andro
For the record, this will be fixed in upcoming release. https://github.com/android/android-test/issues/143
EDIT: This is now fixed in https://github.com/android/android-test/issues/143
Claim:
There is a limitation within the launch(Intent startActivityIntent)
method of the ActivityScenario API. It waits for the Activity to be Lifecycle.STATE.RESUMED
or DESTROYED
and if it isn't within 4.5 seconds then it throws this error.
Context:
My application uses an IndexActivity
to load a config which instructs the application on certain API calls to make. However, immediately after it loads a DialogActivity
and the IndexActivity
goes into STOPPED
. On accepting terms within the DialogActivity
the IndexActivity
goes back into RESUMED
and then ActivityScenario works properly. With my tests, there was a race condition on whether Espresso could click through the terms within 4.5 seconds to get the IndexActivity
to be RESUMED
or whether this error would throw before that. It would take major refactoring to enable another Activity to be launched with ActivityScenario so that was not an option.
The Fix
Within public static <A extends Activity> ActivityScenario<A> launch(Intent startActivityIntent)
of Activity Scenario, check the logic scenario.waitForActivityToBecomeAnyOf(State.RESUMED, State.DESTROYED);
If you can create your own custom Activity Scenario and adjust this line of code to be something like scenario.waitForActivityToBecomeAnyOf(State.STOPPED, State.DESTROYED);
then it will theoretically work for you. You can then use ActivityScenario again to move the Activity into whatever Lifecycle State you want.
OR just use the old https://developer.android.com/reference/androidx/test/rule/ActivityTestRule until Google addresses this in AndroidX Test.
TL;DR
This is happening because the Lifecycle.State of your Activity is not either of the two specific lifecycle states ActivityScenario.Launch()
waits for, RESUMED
or DESTROYED
. Your activity is probably in the background of a dialog or another edge-case situation that was not thought about when creating the API.
For me this was because I had a device plugged in with the screen off and an emulator running. I assumed I was launching to the emulator but I was running it on the device. Since the screen was off, the test was never able to transition to a valid state.