Using Idling Resources in your Espresso Tests

Using Idling Resources in your Espresso Tests
Testing is wow. And UI testing in Android is awesome. Espresso is a UI testing framework for Android. I can say that it was pretty easy and…

Testing is wow. And UI testing in Android is awesome. Espresso is a UI testing framework for Android. I can say that it was pretty easy and you can get used to it in a couple of hours. It’s just like structured English, but in Java/Kotlin.

A simple example from the documentation when using the Espresso framework is this:

@Test
fun greeterSaysHello() {
onView(withId(R.id.name_field)).perform(typeText("Steve"))
onView(withId(R.id.greet_button)).perform(click())
onView(withText("Hello Steve!")).check(matches(isDisplayed()))
}
Note: These tests run under the androidtest package.

But sometimes (or mostly) we are not working on the main thread. We have lots of code that blocks our UI and force us to run on another thread. Since Espresso test is quick and straightforward it doesn’t really wait until our background execution has started, is running, is being finished or has already finished. Therefore, we might need a extra hand…

Introducing to the Idling Resources:

Dependency:

From the documentation of the code the Idling Resources are defined like this:

Now Espresso knows how to wait until some heavy work is executing.

Let’s see an example:

First we need a setup for that Idling Resources. Create a class and implement the `IdlingResource` interface:

Basically we are going to tell Espresso to hold when you see an incremented value here, and continue if this value has reached 0

For making things easy create this helper class:

Let’s use it now:

fun onHeavyWorkButtonClicked() {
EspressoIdlingResource.increment()
viewModelScope.launch(Dispatchers.IO) {
//heavy work happens here
withContext(Dispatchers.Main) {
EspressoIdlingResource.decrement()

//heavy work has ended
}
}
}

Just another simple step. Now we need to tell the UI test that we are using the IdlingResource on the current view:

And we are good to go. Just test the views as usual! Good luck! 👍👌✔

Note: I’ve also refactored this case in a simple Android package:

Super helpful resource:

Other posts from my blog: