Android 测试 RxJava 2

Android testing RxJava 2

测试 RxJava 代码时出错。当我在 ViewModel 中调用 AndroidSchedulers.mainThread() 时,它会发生。有人知道怎么处理吗?

这是我的堆栈跟踪:

java.lang.ExceptionInInitializerError
    ...
    at com.cardsimulator.ui.MainViewModel.executeCommand(MainViewModel.java:56)
    at com.cardsimulator.ui.MainViewModelTest.testExecuteCommand_NormalCommand(MainViewModelTest.java:54)
    ...
Caused by: java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.

您不应将 AndroidSchedulers.mainThead() 用于测试目的。您可以改用 Schedulers.trampoline()。它基本上在当前线程上执行所有任务,没有任何排队,定时重载也使用阻塞睡眠。

您可以使用注入框架(如 Dagger 2)来注入正确的调度程序。或者你可以简单地在你的测试中添加这个:

@BeforeClass
public static void setupTest() {
    RxAndroidPlugins.setInitMainThreadSchedulerHandler(
            __ -> Schedulers.trampoline());
}