End-to-end tests and flakiness
Why it matters
- A flaky end-to-end test that fails now and then teaches the team to ignore red builds, and then real regressions ship.
- Senior interviews ask you to diagnose a flaky test from a log, name the root cause (animation, async work, shared state, environment) and fix it without adding a sleep.
- End-to-end tests are the fewest in the test pyramid (see the Test pyramid for Android lesson), so each one must be reliable.
- Knowing when to use Espresso, the Compose test APIs or UI Automator, and how Espresso
IdlingResource, ComposewaitUntiland Android Test Orchestrator work, is what separates mid-level from senior answers.
The simple explanation
- A flaky test is like a guard who checks a room before the delivery has finished arriving.
- Sometimes the box is there (test passes), sometimes it is still in the hallway (test fails).
- An
IdlingResourceis a sensor that tells the guard "wait, something is still on its way". - Test Orchestrator with
clearPackageDataresets the building between drills, so one drill never leaves a key in the lock for the next.
Why are Android UI tests flaky, and how do you fix them? A test is flaky when it passes and fails on the same code. In Android end-to-end tests the usual cause is that the test checks the screen while the app is still busy: work on a background thread, a network call, or an animation. Espresso and the Compose test rule already wait for the main thread and for Compose to be idle, but they cannot see your own background work. You fix that by telling the framework about it (IdlingResource), by waiting for a condition (waitUntil in Compose), or by removing the async work from the test with fakes. Other causes are state left by previous tests and differences between devices.
| Source | Symptom | Fix |
|---|---|---|
| Background work (coroutines on IO, network) | Assertion runs before data arrives | Fakes, an IdlingResource, or composeRule.waitUntil |
| Animations (Views and system transitions) | View not found or not displayed yet | testOptions { animationsDisabled = true } or turn off animations on the device |
| Real network and real time | Results vary between runs | Fake repositories and an injected Clock |
| Shared state (files, databases, prefs, singletons) | Test B sees data left by test A | Android Test Orchestrator with clearPackageData |
Thread.sleep | Passes on fast machines, fails on slow CI | Remove it; wait for a real condition |
Key APIs. Espresso drives View-based UI and waits for the main thread's message queue and any registered IdlingResource. The Compose test rule (createComposeRule, or createAndroidComposeRule<MainActivity>() when you need a real Activity) waits for recomposition, layout and animations on its virtual clock, and also honours Espresso idling resources. UI Automator works outside your app (system dialogs, notifications, other apps) and has no idling sync, so it polls with wait(Until..., timeout).
Android Test Orchestrator runs each test in its own instrumentation invocation, so a crash or static state in one test does not affect the others. With the runner argument clearPackageData set to "true", it also clears your app's data after each test.
Gradle Managed Devices let Gradle create, start and tear down emulators from definitions in your build file, so local and CI runs use the same device profile. Automated Test Device (ATD) images are trimmed system images made for headless test runs.
Notes
- Espresso's
IdlingResourcehas three methods:getName(),isIdleNow()andregisterIdleTransitionCallback(). Most apps use the ready-madeCountingIdlingResourceinstead of writing one. - Register with
IdlingRegistry.getInstance().register(resource)before the test acts, and unregister in@After. - In Compose,
composeRule.waitUntil(timeoutMillis) { condition }waits for aBooleancondition.composeRule.registerIdlingResource(...)registers a ComposeIdlingResource. - Prefer removing async work from UI tests: inject fake repositories that return immediately, and test the coroutine logic with
runTestin local tests. - Enable Test Orchestrator with
testOptions { execution = "ANDROIDX_TEST_ORCHESTRATOR" }, anandroidTestUtildependency onandroidx.test:orchestrator, andtestInstrumentationRunnerArguments["clearPackageData"] = "true". clearPackageDataclears app data (databases,SharedPreferences, files) after each test, so tests do not depend on order.testOptions { animationsDisabled = true }turns off animations for instrumented tests run from the command line.- Never use
Thread.sleepin a test. Wait for a real condition instead. - UI Automator is for cross-app and system UI, such as a permission dialog. Use Espresso or Compose test APIs for your own screens.
- Gradle Managed Devices run with
./gradlew <deviceName><Variant>AndroidTest, for example./gradlew pixel6api34DebugAndroidTest.
Code example
This end-to-end test drives a Compose login flow in the real Activity with Hilt. The app counts in-flight login calls with Espresso's CountingIdlingResource, and the test registers it, so the assertion runs only after the call has finished.
// app/build.gradle.kts
android {
defaultConfig {
testInstrumentationRunner = "com.example.app.HiltTestRunner" // creates HiltTestApplication
testInstrumentationRunnerArguments["clearPackageData"] = "true"
}
testOptions {
execution = "ANDROIDX_TEST_ORCHESTRATOR"
animationsDisabled = true
managedDevices {
localDevices {
create("pixel6api34") {
device = "Pixel 6"
apiLevel = 34
systemImageSource = "aosp"
}
}
}
}
}
dependencies {
androidTestUtil("androidx.test:orchestrator:<version>")
implementation("androidx.test.espresso:espresso-idling-resource:<version>")
}// main: count work the test framework cannot see
object LoginIdling {
val resource = CountingIdlingResource("login")
}
class AuthRepository @Inject constructor(private val api: AuthApi) {
suspend fun login(email: String, password: String): User {
LoginIdling.resource.increment()
try {
return api.login(email, password)
} finally {
LoginIdling.resource.decrement()
}
}
}
// androidTest
@HiltAndroidTest
class LoginE2ETest {
@get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1)
val composeRule = createAndroidComposeRule<MainActivity>()
@Before
fun setUp() {
hiltRule.inject()
IdlingRegistry.getInstance().register(LoginIdling.resource)
}
@After
fun tearDown() {
IdlingRegistry.getInstance().unregister(LoginIdling.resource)
}
@Test
fun loginShowsWelcomeScreen() {
composeRule.onNodeWithTag("emailField").performTextInput("ada@example.com")
composeRule.onNodeWithTag("passwordField").performTextInput("secret")
composeRule.onNodeWithTag("loginButton").performClick()
// Waits for Compose to be idle and for LoginIdling to reach zero.
composeRule.onNodeWithText("Welcome, Ada").assertIsDisplayed()
}
}- The Hilt rule has
order = 0so the graph exists before the Activity starts. A Hilt test module (not shown) replacesAuthApiwith a fake, so no real server is involved. CountingIdlingResourceis idle when its counter is zero; thefinallyblock keeps the count right even when the call throws or is cancelled.- Without production hooks, the alternative is
composeRule.waitUntil(5_000) { composeRule.onAllNodesWithText("Welcome, Ada").fetchSemanticsNodes().isNotEmpty() }. - With the orchestrator and
clearPackageData, each test starts with empty app data, so a saved session from an earlier test cannot skip the login screen. - Run it on the managed device with
./gradlew pixel6api34DebugAndroidTest.
Run the idea in plain Kotlin
class AsyncTask {
var completed = false
fun execute() { completed = true }
}
class IdlingResource {
private val tasks = mutableListOf<AsyncTask>()
fun register(task: AsyncTask) { tasks.add(task) }
fun isIdle(): Boolean { return tasks.all { it.completed } }
}
fun runWithoutIdling(): Boolean {
val task = AsyncTask()
val idling = IdlingResource()
idling.register(task)
// Assert before the task runs -- simulates no idling
val result = task.completed
task.execute()
return result
}
fun runWithIdling(): Boolean {
val task = AsyncTask()
val idling = IdlingResource()
idling.register(task)
task.execute()
// Assert only after idling confirms work is done
return idling.isIdle() && task.completed
}
fun main() {
println("=== E2E flakiness simulation ===")
println("")
println("Without idling (assert before work):")
val flaky = runWithoutIdling()
println(" assertion sees completed = " + flaky + " (flaky: false means it raced)")
println("")
println("With idling (assert after work):")
val stable = runWithIdling()
println(" assertion sees isIdle = " + stable + " (stable: true means it waited)")
println("")
println("Multiple async tasks:")
val tasks = listOf(AsyncTask(), AsyncTask(), AsyncTask())
val idling = IdlingResource()
tasks.forEach { idling.register(it) }
println(" Before any work, isIdle = " + idling.isIdle())
tasks[0].execute()
println(" After 1 of 3, isIdle = " + idling.isIdle())
tasks[1].execute()
tasks[2].execute()
println(" After 3 of 3, isIdle = " + idling.isIdle())
println("")
println("Lesson: without idling the test races; with idling it is deterministic.")
}Expected output:
=== E2E flakiness simulation ===
Without idling (assert before work):
assertion sees completed = false (flaky: false means it raced)
With idling (assert after work):
assertion sees isIdle = true (stable: true means it waited)
Multiple async tasks:
Before any work, isIdle = false
After 1 of 3, isIdle = false
After 3 of 3, isIdle = true
Lesson: without idling the test races; with idling it is deterministic.
In production
- The nightly suite's
LoginE2ETestfailed every few runs: the welcome text was not found. - Someone added
Thread.sleep(3000)before the assertion. Failures dropped but did not stop on slower CI machines, and every run got slower. - Developers started skipping the end-to-end stage, and a real regression in the login flow later shipped.
- Replaced the sleep with a
CountingIdlingResourcearound the login call, registered in the test, and replaced the real backend with a fakeAuthApithrough a Hilt test module. - Enabled Android Test Orchestrator with
clearPackageData, which also fixed a second flake where a saved session from an earlier test skipped the login screen. - Ran the test many times in a row on a managed device before turning the stage back on for pull requests.
- An Espresso test that opened a dialog failed on CI with "view not displayed" but passed on every developer's phone.
- Developers had turned off animations in developer options on their phones; the CI emulator still had them on, so the dialog was mid-animation when Espresso checked it.
- Set
testOptions { animationsDisabled = true }so command-line runs always disable animations. - Moved CI to a Gradle Managed Device definition, so CI and local runs use the same emulator profile and settings.
- Documented that tests must not depend on developer-option settings.
Common mistakes
- Adding Thread.sleep to fix a flaky test. It turns a race into a slower race: wasted time on fast devices, still too short on slow ones. Wait for the real condition with an
IdlingResourceorwaitUntil. - Using the real network or the real clock. Latency and time vary between runs. Inject a fake repository (see the Fakes vs mocks lesson) and a test
Clock. - Letting tests share app data. Without the orchestrator and
clearPackageData, a login saved by one test changes what the next test sees. Clear data between tests so order does not matter. - Forgetting to unregister an IdlingResource. A resource left in
IdlingRegistrycan affect later tests in the same process. Register in@Beforeand unregister in@After. - Putting an assertion inside waitUntil. The lambda must return a
Boolean; an assertion throws instead of being retried. CheckfetchSemanticsNodes().isNotEmpty()or use thewaitUntil...Existshelpers. - Using UI Automator for your own screens. It does not sync with your app's idle state, so it needs explicit waits and is slower. Use Espresso or Compose test APIs in-app; keep UI Automator for system and cross-app UI.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“A Compose end-to-end test fails sometimes because a node is not found, though it does appear on screen. What do you check first?”
“What is the difference between Espresso and UI Automator, and when would you use each?”
“How does Android Test Orchestrator reduce flakiness?”
“A team has 200 end-to-end tests and 15 of them are flaky. What is your plan?”
Quiz
What is the most common root cause of flaky Android end-to-end tests?
What does the clearPackageData runner argument do with Android Test Orchestrator?
Which approach best fixes flakiness caused by a real network call in an end-to-end test?
Which methods make up Espresso's IdlingResource interface?
0 of 4 answered
Mini task
Fix a flaky Compose end-to-end test in 15 minutes
-
Reproduce. Pick an instrumented test for a screen that loads data. Run it several times, for example
./gradlew connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.example.ListE2ETest, and note how often it fails. -
Diagnose. Check: (a) does the data come from a real network call or a background coroutine? (b) does the test use
Thread.sleep? (c) could an earlier test have left data behind? Write down which apply. -
Remove async from the test. Replace the real repository or API with a fake through a Hilt test module. If some background work must stay, add a
composeRule.waitUntilcondition or register aCountingIdlingResource. Delete anyThread.sleep. -
Isolate tests. In
build.gradle.kts, settestOptions { execution = "ANDROIDX_TEST_ORCHESTRATOR"; animationsDisabled = true }, addtestInstrumentationRunnerArguments["clearPackageData"] = "true"indefaultConfig, and addandroidTestUtil("androidx.test:orchestrator:<version>"). -
Pin the device. Define a Gradle Managed Device and run
./gradlew <deviceName>DebugAndroidTest. -
Verify. Run the test 20 times. It must pass every time; if not, go back to step 2.
Done condition: 20 out of 20 passes, no Thread.sleep, a fake or idling sync for the async work, and the orchestrator enabled in Gradle.