An Espresso login test passes locally but flakes on CI while the sign-in network call completes; how do you fix it with an IdlingResource?
answer
- work Espresso cannot see
- a counter, not a sleep
- increment before, decrement in finally
- IdlingRegistry in @Before and @After
- 26 seconds, then an exception
basics
~20 sThe sign-in call runs off the main thread, so Espresso asserts before the response arrives. Wrap the call in a CountingIdlingResource (increment before, decrement in finally), register it with IdlingRegistry in @Before and unregister it in @After.
solid answer
~40 sThe click starts the sign-in request on a background thread and returns, the main queue empties, and Espresso runs the next assertion; on a slow CI emulator the response lands after it. Instead of a sleep, make the work visible. In app code, hold a `CountingIdlingResource("network")` from the `espresso-idling-resource` artifact, call `increment()` before the request and `decrement()` in a `finally` block once the result is back on the main thread. In the test, call `IdlingRegistry.getInstance().register(resource)` in `@Before` and `unregister` in `@After`. Espresso then treats the app as busy while the counter is above zero. A resource that never returns to zero fails the test with `IdlingResourceTimeoutException` after 26 seconds, which usually means a path that forgot to decrement.
code
kotlin · 16 linesobject NetworkIdling {
val resource = CountingIdlingResource("network")
}
class LoginRepository(private val api: AuthApi) {
// Called from viewModelScope on the main thread; api.signIn suspends
// while the HTTP client works on its own threads.
suspend fun signIn(email: String, password: String): Session {
NetworkIdling.resource.increment()
try {
return api.signIn(email, password)
} finally {
NetworkIdling.resource.decrement()
}
}
}go deeper
Recall that Espresso cannot see network calls on background threads and that an idling resource, not a sleep, is how you make it wait.
Explain how CountingIdlingResource decides idleness, why decrement goes in finally, and why IdlingRegistry registration belongs in @Before with unregistration in @After.
Trace the race from click to assertion, place the decrement after the result reaches the main thread, and read IdlingResourceTimeoutException as an unbalanced counter rather than a slow server.
Decide whether idling code lives in production classes, a debug-only variant or an injected test binding, weighing encapsulation against how easily every new async path gets covered.
## Why the test flakes Espresso waits before every action and assertion until the main thread's message queue has nothing due, no `AsyncTask` is running and every **registered idling resource** is idle. A sign-in request made through an HTTP client runs on that client's own threads, which are none of those things. The sequence on CI is: 1. The test performs `click()` on the sign-in button. 2. The click handler starts the request on a background thread and returns at once. 3. The main queue is empty, so Espresso considers the app idle. 4. The test checks for the welcome text, which is not there yet, and fails. On a fast workstation the response sometimes arrives between steps 3 and 4, which is why the test looks fine locally. The emulator on CI is slower, so the race goes the other way more often. The same root cause shows up in other forms: an image that arrives after the assertion, a list that fills after a database read, a message that appears late. Each is work Espresso was never told about. ## The fix: a CountingIdlingResource An **idling resource** is an object that tells Espresso whether some piece of the app is busy. `CountingIdlingResource` is the ready-made one: it keeps a counter, is idle at zero and busy above it, and its counter can be changed from any thread. It ships in the small `androidx.test.espresso:espresso-idling-resource` artifact, which Android's guidance recommends placing in the app so the app itself marks its asynchronous work, while tests only register and unregister. - Call `increment()` just before the request starts. - Call `decrement()` in a `finally` block, so error and cancellation paths decrement too. - Decrement only once the result is back on the main thread. If you decrement on the network thread before the result is posted, there is a short window where the counter is zero and the UI has not been updated yet. - Give each resource a distinct name; the name appears in Espresso's timeout messages. Because the app code raises and lowers the counter, the test itself stays a plain sequence of Espresso steps with no waits in it. In the test, register through `IdlingRegistry.getInstance().register(...)` and unregister through `unregister(...)`. The documentation calls `IdlingRegistry` the only supported way to register idling resources; the older static `Espresso.registerIdlingResources` is deprecated in its favour. ## Registration timing and clean-up - **Register before you need it.** A resource takes effect only after Espresso's first call to its `isIdleNow()`, which happens at the next Espresso action. Registering in `@Before` covers the first line of every test. - **Unregister in `@After`.** `IdlingRegistry` is a process-wide singleton. A resource left registered, and left busy, stalls later tests that never asked for it. - **Keep the resource simple.** Android's guidance says idling resources should hold simple state and no references to `View` objects. ## When it never goes idle Espresso bounds the wait. With Espresso 3.7.0 defaults it logs a warning naming the busy resources after 5 seconds and throws `IdlingResourceTimeoutException` after 26 seconds; `IdlingPolicies.setIdlingResourceTimeout` changes the limit. In practice a timeout almost always means a code path that incremented and never decremented, typically an exception or an early return. Decrementing below zero is the opposite bug: `CountingIdlingResource` throws `IllegalStateException` when the counter would go negative. ## Other ways to make the work visible | Option | Good for | |---|---| | `CountingIdlingResource` | Wrapping individual calls you control | | `UriIdlingResource` | Back-to-back requests: the counter must stay at zero for a while before it counts as idle | | `IdlingThreadPoolExecutor` | An executor whose running tasks Espresso should track | | A custom `IdlingResource` | Idleness that is a condition rather than a count | `CountingIdlingResource` ships in `espresso-idling-resource`; the executor and URI variants come from Espresso's companion idling libraries, published alongside it as `idling-concurrent` and `idling-net`. A custom resource implements `getName()`, `isIdleNow()` and `registerIdleTransitionCallback(...)`. Call the callback's `onTransitionToIdle()` from the code that finishes the work, not from inside `isIdleNow()`, so Espresso does not make a second, unnecessary check. ## What not to do The documentation names the workarounds this replaces: `Thread.sleep()` makes the suite slow and still fails on slower devices; retry loops waste CPU; a `CountDownLatch` needs a timeout and adds complexity. If you do not want the idling code in the release build at all, Android's guidance offers alternatives: limit it to a debug build variant, or inject it through dependency injection in the test build.
- Why register the idling resource in @Before rather than right before the assertion that needs it?A resource takes effect only after Espresso first calls its `isIdleNow()`, which happens at the next Espresso action. Registering in `@Before` means it already applies to the first line of each test. Registering mid-test still works from the next action on, but if the request started earlier the click that triggered it was not covered. Unregister in `@After` because `IdlingRegistry` is shared by the whole process.
- The test now fails with IdlingResourceTimeoutException naming the network resource; what do you look for?A path that called `increment()` and never `decrement()`: an exception, a cancelled coroutine or an early return outside the `finally`. With Espresso 3.7.0 defaults the warning appears after 5 seconds and the exception after 26. Raising the timeout with `IdlingPolicies.setIdlingResourceTimeout` only hides an unbalanced counter; balance it with `try`/`finally` instead.
- When would you write your own IdlingResource instead of using CountingIdlingResource?When busy means a condition rather than a count, such as a cache that is warming or a state machine that must reach a given state. Implement `getName()`, `isIdleNow()` and `registerIdleTransitionCallback(...)`, keep only simple state with no `View` references, and call `onTransitionToIdle()` from the code that finishes the work, never from inside `isIdleNow()`.
A cloakroom attendant who will not lock up while any ticket is still out: each coat handed in is an increment, each coat collected a decrement, and closing time arrives only at zero. Lose track of one returned coat and the room stays open until the manager's deadline ends the night with an error.
- Add Thread.sleep(3000) after the click because the CI emulator is slower
- Decrement the counter only when the request succeeds
- Call onTransitionToIdle() from inside isIdleNow() whenever the work is done
- Espresso.registerIdlingResources is the current registration API
- There is no need to unregister an idling resource once the test ends
Assumes Espresso 3.7.0: IdlingRegistry is the supported registry and busy idling resources time out after 26 seconds by default.