Handle executor idle state with Espresso and an IdlingResource
import android.support.annotation.NonNull; | |
import android.support.test.espresso.Espresso; | |
import android.support.test.espresso.IdlingResource; | |
import org.junit.rules.ExternalResource; | |
import java.util.concurrent.Executor; | |
import java.util.concurrent.ThreadPoolExecutor; | |
public class ExecutorTestRule extends ExternalResource { | |
private ThreadPoolExecutor workerExecutor = (ThreadPoolExecutor) MainDependencies.instance.workerExecutor; | |
private IdlingResource idlingResource; | |
@Override | |
protected void before() throws Throwable { | |
final ResourceCallbackExecutor workerResourceCallbackExecutor = | |
new ResourceCallbackExecutor(MainDependencies.instance.workerExecutor); | |
MainDependencies.instance.workerExecutor = workerResourceCallbackExecutor; | |
idlingResource = new IdlingResource() { | |
@Override | |
public String getName() { | |
return "ExecutorIdlingResource"; | |
} | |
@Override | |
public boolean isIdleNow() { | |
return workerExecutor.getActiveCount() == 0 | |
&& workerExecutor.getQueue().isEmpty(); | |
} | |
@Override | |
public void registerIdleTransitionCallback(ResourceCallback callback) { | |
workerResourceCallbackExecutor.setCallback(callback); | |
} | |
}; | |
Espresso.registerIdlingResources(idlingResource); | |
} | |
@Override | |
protected void after() { | |
MainDependencies.instance.workerExecutor = workerExecutor; | |
Espresso.unregisterIdlingResources(idlingResource); | |
} | |
private static class ResourceCallbackExecutor implements Executor { | |
private final Executor executor; | |
private IdlingResource.ResourceCallback callback; | |
ResourceCallbackExecutor(Executor executor) { | |
this.executor = executor; | |
} | |
@Override | |
public void execute(@NonNull final Runnable command) { | |
executor.execute(new Runnable() { | |
@Override | |
public void run() { | |
command.run(); | |
callback.onTransitionToIdle(); | |
} | |
}); | |
} | |
void setCallback(IdlingResource.ResourceCallback callback) { | |
this.callback = callback; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment