Thread pool IdlingResource for Espresso

I wrote an IdlingResource for Espresso that works with thread pools.

You can find a repository in my github with an example application and test.

The IdlingResource is in the androidTest folder, the file is named ThreadIdlingResourceMonitor.java.

Usage

To know how to use it, check the Espresso test called SuccessTestCase.

Remember that you need to pass to the IdlingResource the exact same instance of the ThreadPool you want to monitor.
Otherwise the count of the spawned threads will differ between the Espresso test and the application.

Basically you need to register the IdlingResource before calling onView(), for example in the @Before step:

  private IdlingResource idlingResource;

  @Before
  public void setUp() {
    idlingResource = new ThreadIdlingResourceMonitor(
        ExecutorFactory.getInstance().getCachedThreadPoolExecutor());
    Espresso.registerIdlingResources(idlingResource);
  }

Remember to unregister it when you don’t need it anymore, a good place is in @After:

  @After
  public void tearDown() {
    Espresso.unregisterIdlingResources(idlingResource);
  }

The main / target application is just a simple application with two buttons that will spawn two different threads from the threadpool to launch an activity with a simple text.

SuccessTestCase will pass because it uses my IdlingResource while FailedTestCase will fail because it won’t use the IdlingResource hence it won’t correctly wait before checking the text in the new Activity.

How it works

I created my IdlingResource starting from the Espresso code, more precisely the AsyncTaskPoolMonitor class, which is used by Espresso to wait for an AsyncTask to complete.
Please refer to that class for more details.

Custom IdlingResources are loaded via IdlingResourceRegistry class as you can see from the Espresso class.