Schedulers.io() 在我的单元测试中抛出 NullPointerException

Schedulers.io() Throwing NullPointerException in my Unit Tests

我正在尝试为下面的 ViewModel 方法创建单元测试,它使用RxJava/RxKotlin

fun doLogin(address: String, serial: String) {
    mLoading.value = true
    mCompositeDisposable.add(
        mRepository
            .doLogin(address, createJsonArray(serial, generatePinJSON()))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeBy(
                onSuccess = { json ->
                    /** CODE **/
                },
                onError = { error ->
                    /** CODE **/
                }
            )
    )
}

但是在测试方法中调用Schedulers.io()时,抛出NullPointerException。

我尝试使用以下方法:

https://medium.com/@dbottillo/how-to-unit-test-your-rxjava-code-in-kotlin-d239364687c9(创建规则)

https://medium.com/@PaulinaSadowska/writing-unit-tests-on-asynchronous-events-with-rxjava-and-rxkotlin-1616a27f69aa(将调度程序传递给 ViewModel)

在这两种方法中,它说在测试方法中使用 Schedulers.trampoline()。但它仍然抛出错误。

我 运行 没有选择,无法弄清楚为什么会这样。

有人可以帮助我吗?

谢谢。

根据我的经验,你得到 null 是因为你没有模拟 mRepository.doLogin。尝试在测试函数的开头添加它

whenever(mRepository.doLogin).thenReturn(...)