Synchronizing Espresso with Custom Threads using Counting Idling Resource
Espresso is a great framework for testing your apps’ UI. The features and accessibility of this testing framework is increasing at a very fast pace thanks to the folks over at Google. The Espresso test recorder — a tool for automatically generating Espresso test code just by using an app in Emulator is out of BETA. It makes writing trivial tests a piece of cake however it still doesn’t support certain View Matchers & assertions. For that you need to write the test code by hand.
It’s not recommended to use Espresso Test Recorder to generate test code for your app since you won’t be able to learn the ins and outs of the framework without getting your hands dirt with the code yourself. Think of this tool as tutorial for learning Espresso framework.
One of the things that Espresso Test Recorder doesn’t offer is syncing Espresso with custom background threads. This means, Retrofit, okhttp and other libraries that make use of threads that aren’t pooled by Espresso won’t work properly with the testing framework. As a result your tests will fail.
Espresso provides very easy APIs to over this limitation in the form of idling resource. You can write an Idling Resource to match your needs and register in your Espresso Test class or use the idling resources that come bundled with the framework like CountingIdling Resource. It’s the simplest of the Idling Resources to wrap your head around quickly.
How CountingIdling Resource Works?
CoutingIdlingResource works on the simple concept of increments and decrements. When you dispatch a task on a background thread, you increment the Counting Idling Resource. It’s perceived by Espresso as if the Main UI Thread is still busy. Once your background thread/network call completes, decrement the Counting Idling Resource. As a result Espresso will resume executing test code. Easy peasy ain’t it?
The following code demonstrates how CountingIdlingResource can be used by Retrofit to make Espresso tests a success.