---
title: Synchronisation and IdlingResources | TestingBot
description: The login tests from chapter 2 fail because Espresso checked the result
  before the app had it. This chapter explains what Espresso waits for on its own,
  why…
source_url:
  html: https://testingbot.com/resources/courses/espresso/synchronisation-and-idling-resources
  md: https://testingbot.com/resources/courses/espresso/synchronisation-and-idling-resources.md
---

Course

[Espresso Android Testing in Kotlin](https://testingbot.com/resources/courses/espresso)

Chapter 5 of 10

1. [1 Espresso Android Testing Tutorial in Kotlin](https://testingbot.com/resources/courses/espresso)
2. [2 Gradle Setup and Your First Espresso Run](https://testingbot.com/resources/courses/espresso/gradle-setup)
3. [3 ViewMatchers, ViewActions and ViewAssertions](https://testingbot.com/resources/courses/espresso/matchers-actions-assertions)
4. [4 Lists with RecyclerViewActions, and Espresso-Intents](https://testingbot.com/resources/courses/espresso/recyclerview-and-intents)
5. [5 Synchronisation and IdlingResources](https://testingbot.com/resources/courses/espresso/synchronisation-and-idling-resources)
6. [6 Test Isolation, Orchestrator and the Robot Pattern](https://testingbot.com/resources/courses/espresso/test-isolation-and-robots)
7. [7 Building the App APK and the Test APK](https://testingbot.com/resources/courses/espresso/build-the-apks)
8. [8 Run Espresso Tests on TestingBot](https://testingbot.com/resources/courses/espresso/run-on-testingbot)
9. [9 Running Espresso in CI with GitHub Actions](https://testingbot.com/resources/courses/espresso/ci-github-actions)
10. [10 Espresso Knowledge Check](https://testingbot.com/resources/courses/espresso/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 5 of 10 Intermediate 7 min read 2 quick checks Updated Nov 2026 

# Synchronisation and IdlingResources
On this page
1. [What Espresso waits for](https://testingbot.com#what-espresso-waits-for)
2. [Why not just sleep?](https://testingbot.com#why-not-just-sleep)
3. [IdlingResources: tell Espresso about your work](https://testingbot.com#idlingresources-tell-espresso-about-your-work)
4. [Keeping test code out of the app](https://testingbot.com#keeping-test-code-out-of-the-app)
5. [When waiting is legitimate](https://testingbot.com#when-waiting-is-legitimate)

The login tests from chapter 2 fail because Espresso checked the result before the app had it. This chapter explains what Espresso waits for on its own, why that covers most screens, and how to tell it about the work it cannot see, so that the tests pass without a single `Thread.sleep`.

## What Espresso waits for[#](https://testingbot.com#what-espresso-waits-for)

Before every `perform()` and every `check()`, Espresso waits until the app is idle. "Idle" has a precise meaning. All of these must be true at the same moment:

1. The **main thread's message queue** has no messages due now. Layout passes, click handlers, `Handler.post` calls and lifecycle callbacks all go through this queue.
2. The **`AsyncTask` thread pool** has no running tasks. `AsyncTask` is deprecated, but Espresso still watches its executor.
3. Every **registered IdlingResource** reports that it is idle.

Only then does Espresso run the action or the check, on the main thread. That is why a test can tap Log in and then immediately check the next screen when the work happens on the main thread: the click handler, the `startActivity` call and the new activity's layout are all messages in the queue, and Espresso waits until they have been processed.

What Espresso does **not** see:

- Threads you start yourself: an `Executor`, a plain `Thread`, Kotlin coroutines on `Dispatchers.IO` or `Dispatchers.Default`, RxJava schedulers.
- Networking libraries' own thread pools.
- Animations (which is why chapter 1 disabled them).
- Anything delayed with `Handler.postDelayed` far enough in the future that the queue has nothing due now.

Espresso Shop's login is exactly the first case:

```kotlin
object AuthService {
    private val executor = Executors.newSingleThreadExecutor()
    private val main = Handler(Looper.getMainLooper())

    fun login(user: String, password: String, done: (Boolean) -> Unit) {
        executor.execute {
            Thread.sleep(1500) // a slow network call
            val ok = user == "alice" && password == "secret"
            main.post { done(ok) }
        }
    }
}
```

While the background thread sleeps, the main thread's queue is empty, so Espresso considers the app idle and runs the check at once. The error label is still empty, and the test fails with `Got: view.getText() was ""`.

A screen loads its data with `viewModelScope.launch(Dispatchers.IO) { repo.load() }` and the Espresso check on the list runs before the data arrives. Why?

 Espresso does not wait for view models at all, even on the main thread The work runs on an IO thread that Espresso does not watch, so the main thread looks idle Coroutines are not supported in instrumented tests

Espresso only waits for the main thread's queue, the AsyncTask pool and registered IdlingResources. A coroutine on Dispatchers.IO is none of those, so Espresso sees an idle app while the data is still loading. The fix is an IdlingResource for that work, or an injectable dispatcher that a test can make visible.

## Why not just sleep?[#](https://testingbot.com#why-not-just-sleep)

The obvious fix works. With `Thread.sleep(2000)` after the click, `wrongPasswordShowsError` passed in this course's run. It is still the wrong fix:

- **It is slow every time.** The sleep costs two seconds even when the login answers in 200 milliseconds, and it adds up over a suite and over every CI run.
- **It is a guess.** On a slow emulator, a busy CI machine or a real device on a bad network, the work takes longer than the guess, and the test fails at random. That is how flaky suites are born. The [Flaky Tests course](https://testingbot.com/resources/courses/flaky-tests) covers the pattern in general.
- **It hides the information.** The app knows exactly when the login finishes. A sleep throws that knowledge away.

## IdlingResources: tell Espresso about your work[#](https://testingbot.com#idlingresources-tell-espresso-about-your-work)

An **IdlingResource** is an object the app updates while it is busy, and Espresso checks before every action. The simplest implementation, `CountingIdlingResource`, is a counter: `increment()` when work starts, `decrement()` when it ends, idle when the counter is zero.

The class lives in a small library that the **app** depends on, because the app code is what updates it:

```kotlin
// app/build.gradle.kts
implementation("androidx.test.espresso:espresso-idling-resource:3.7.0")
```

Then the app reports its work:

```kotlin
object AuthService {
    // Espresso cannot see this background thread, so the app reports it.
    val idlingResource = CountingIdlingResource("AuthService")

    private val executor = Executors.newSingleThreadExecutor()
    private val main = Handler(Looper.getMainLooper())

    fun login(user: String, password: String, done: (Boolean) -> Unit) {
        idlingResource.increment()
        executor.execute {
            Thread.sleep(1500) // a slow network call
            val ok = user == "alice" && password == "secret"
            main.post {
                done(ok)
                idlingResource.decrement()
            }
        }
    }
}
```

Note where `decrement()` is: **after** `done(ok)` has updated the UI, inside the same main-thread message. If you decrement on the background thread before posting the result, there is a moment where the counter says idle but the UI has not changed yet, and the check can slip into it.

The test registers the resource before each test and unregisters it afterwards:

```kotlin
@Before
fun registerIdlingResource() {
    IdlingRegistry.getInstance().register(AuthService.idlingResource)
}

@After
fun unregisterIdlingResource() {
    IdlingRegistry.getInstance().unregister(AuthService.idlingResource)
}
```

With that in `LoginTest`, both tests pass, with no change to the test bodies. After the click, Espresso sees the counter at 1, waits until it drops to 0 (about 1.5 seconds), and then runs the check. Each test now takes exactly as long as the login does.

Always unregister in `@After`. The registry is global for the whole instrumentation process, so a resource left registered by one test class affects every class that runs after it.

After adding a CountingIdlingResource, a test now fails after a long wait with an error about an idling resource that never became idle. What is the most likely bug?

 The test forgot `closeSoftKeyboard()` The resource was registered in `@Before` A code path calls `increment()` but never `decrement()`, for example when the request throws

A counter that never returns to zero means Espresso waits until its idling timeout and then fails. Every `increment()` needs a matching `decrement()` on every path, including errors: put it in a `finally` block or the error callback as well as the success one.

## Keeping test code out of the app[#](https://testingbot.com#keeping-test-code-out-of-the-app)

`AuthService` now carries a test helper. That is the most common objection to IdlingResources, and there are three ways teams handle it:

- **Accept it.** `espresso-idling-resource` is a tiny library with no other dependencies, and a counter that is never registered costs next to nothing. This is what the sample does, and Google's own samples do the same.
- **Inject it.** Give the class an interface such as `BusyTracker`, use a no-op version in production and a `CountingIdlingResource`-backed one from the test, through your dependency injection setup.
- **Wrap the executor.** If the work runs on an executor you create, the `androidx.test.espresso.idling:idling-concurrent` artifact has `IdlingThreadPoolExecutor`, an executor that is its own IdlingResource. Swap it in for tests and every task on it is tracked automatically.

For Kotlin coroutines, the usual pattern is the second one: inject the dispatchers, and in tests use a dispatcher whose work Espresso can see.

## When waiting is legitimate[#](https://testingbot.com#when-waiting-is-legitimate)

IdlingResources are for work **inside** your app. When a test has to wait for something outside it, such as a push notification or a system dialog, Espresso cannot help at all, and an explicit wait with a timeout is the right tool. UI Automator has them (`device.wait(Until.hasObject(...), 5000)`). Keep such waits to the few tests that cross the app boundary.

With synchronisation fixed, all the tests pass individually. Run them together and the product list tests still fail, for a different reason.

[Previous · Chapter 4 Lists with RecyclerViewActions, and Espresso-Intents](https://testingbot.com/resources/courses/espresso/recyclerview-and-intents) [Next · Chapter 6 Test Isolation, Orchestrator and the Robot Pattern](https://testingbot.com/resources/courses/espresso/test-isolation-and-robots)

On this page

1. [What Espresso waits for](https://testingbot.com#what-espresso-waits-for)
2. [Why not just sleep?](https://testingbot.com#why-not-just-sleep)
3. [IdlingResources: tell Espresso about your work](https://testingbot.com#idlingresources-tell-espresso-about-your-work)
4. [Keeping test code out of the app](https://testingbot.com#keeping-test-code-out-of-the-app)
5. [When waiting is legitimate](https://testingbot.com#when-waiting-is-legitimate)

Certification

Earn the free, resume-worthy TestingBot Espresso Certification for this course.

[How it works](https://testingbot.com/resources/courses/espresso/certification)
