Recipe Wait for execution - nenick/espresso-macchiato GitHub Wiki

IdlingResources is the concept from Espresso to sync with executions on non ui threads.

See also

Use IdlingResource concept

Add idling resources as compile time dependency

compile 'com.android.support.test.espresso:espresso-idling-resource:2.2.2'

Implement a basic counting idling resource

public class MyIdlingResource implements IdlingResource {

    private static MyIdlingResource instance;

    private int count = 0;
    private ResourceCallback callback;

    public static MyIdlingResource instance() {
        if(instance == null) {
            instance = new MyIdlingResource();
        }
        return instance;
    }

    private MyIdlingResource() {
        // just hide constructor
    }

    public void increment() {
        count++;
    }

    public void decrement() {
        count--;
        if(count < 0) throw new IllegalStateException();
        if(count == 0 && callback != null) callback. onTransitionToIdle() 
    }

    @Override public String getName() {
        return MyIdlingResource.class.getSimpleName();
    }

    @Override public boolean isIdleNow() {
        return count == 0;
    }

    @Override public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
        this.callback = resourceCallback;
    }
}

In your test register your idling resource

Espresso.registerIdlingResources(MyIdlingResource.instance());

Use idling resource for non ui thread tasks

public void myAsyncMethod() {
    myIdlingResource.increment();
    ... tasks ...
    myIdlingResource.decrement();
}

Here a more stable usage example

public void myAsyncMethod() {
    try {
        myIdlingResource.increment();
        ... tasks ...
    } finally {
        myIdlingResource.decrement();
    }
}

CountingIdlingResource from espresso-contrib

Espresso self provides an implementation of the IdlingResource but it lead in much unused dependencies for your application.

See also