tezvyn:

ActivityScenario: Test Your Android Activities in Isolation

AI-drafted, machine-checkedSource: developer.android.comintermediate

ActivityScenario lets you launch and control an Android Activity's lifecycle within an instrumented test. Use it to verify UI behavior during events like screen rotation or process death, isolating the component for reliable testing.

WHY IT EXISTS Testing Android Activities is complex because they are tied to the OS and a complicated lifecycle. Manually triggering states like process death or screen rotation is difficult and unreliable. ActivityScenario was created to provide a stable, official API for driving Activities through these states in a controlled test environment.

THE MENTAL MODEL Think of ActivityScenario as a remote control for a single Activity. Instead of launching your whole app to test one screen, you use the scenario to launch just that screen in a hermetic test environment. You can then use the remote to press buttons like "rotate screen," "send to background," or "destroy and recreate," and then check if the screen's UI is still correct.

HOW IT WORKS ActivityScenario is part of the AndroidX Test library. You launch a scenario using ActivityScenario.launch(MyActivity.class). This creates and brings the Activity to the RESUMED state. You can then use methods like moveToState(Lifecycle.State.CREATED) to simulate lifecycle events. To interact with the Activity's UI, for example with Espresso, you use scenario.onActivity { activity -> ... } to get a safe reference to the Activity instance.

WHEN TO USE IT Use ActivityScenario for instrumented UI tests that need to verify an Activity's behavior. It's ideal for testing state restoration after a configuration change (e.g., rotating the device), checking for memory leaks, or ensuring correct behavior when the Activity is paused and resumed. It is the standard for modern Android UI testing, replacing the older ActivityTestRule.

WHEN NOT TO USE IT Don't use ActivityScenario for simple unit tests that don't involve the Android framework or an Activity's lifecycle. For testing ViewModels or business logic, a plain JUnit test is faster and more appropriate. It is also not designed for testing complex navigation flows between multiple Activities; for that, you would orchestrate tests at a higher level.

ONE CANONICAL EXAMPLE A common test is to verify that text entered into an EditText survives a screen rotation. You would launch the scenario, use Espresso to type text into the field, then call scenario.recreate() to simulate the rotation. Finally, you'd use Espresso again to assert that the EditText still contains the original text, confirming your state-saving logic works.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.