Last active
March 20, 2017 10:04
-
-
Save sagix/bc612338d88f383161ba1831bf9a4475 to your computer and use it in GitHub Desktop.
Handle executor idle state with Espresso and an IdlingResource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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