-
Notifications
You must be signed in to change notification settings - Fork 9
Recipe Wait for execution
Nico Küchler edited this page Apr 2, 2016
·
1 revision
IdlingResources is the concept from Espresso to sync with executions on non ui threads.
See also
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();
}
}
Espresso self provides an implementation of the IdlingResource but it lead in much unused dependencies for your application.
See also