Skip to content

Instantly share code, notes, and snippets.

@A-Zaiats
Last active May 9, 2018 17:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A-Zaiats/5577863138a4b9d972d15239ab4a0101 to your computer and use it in GitHub Desktop.
Save A-Zaiats/5577863138a4b9d972d15239ab4a0101 to your computer and use it in GitHub Desktop.
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.util.concurrent.Callable;
import io.reactivex.Scheduler;
import io.reactivex.android.plugins.RxAndroidPlugins;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
public class RxJunitRule implements TestRule {
private final Function<Scheduler, Scheduler> handler = new Function<Scheduler, Scheduler>() {
@Override
public Scheduler apply(@NonNull Scheduler scheduler) throws Exception {
return Schedulers.trampoline();
}
};
private final Function<Callable<Scheduler>, Scheduler> androidInitHandler = new Function<Callable<Scheduler>, Scheduler>() {
@Override
public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception {
return Schedulers.trampoline();
}
};
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
clearHooks();
applyTestHooks();
base.evaluate();
clearHooks();
}
};
}
private void clearHooks() {
RxJavaPlugins.reset();
RxAndroidPlugins.reset();
}
private void applyTestHooks() {
RxJavaPlugins.setComputationSchedulerHandler(handler);
RxJavaPlugins.setIoSchedulerHandler(handler);
RxJavaPlugins.setNewThreadSchedulerHandler(handler);
RxAndroidPlugins.setMainThreadSchedulerHandler(handler);
RxAndroidPlugins.setInitMainThreadSchedulerHandler(androidInitHandler);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment