【问题标题】:Android testing RxJava 2Android 测试 RxJava 2
【发布时间】:2018-12-17 12:13:00
【问题描述】:

测试 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.

【问题讨论】:

    标签: android unit-testing junit rx-java rx-java2


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      相关资源
      最近更新 更多