androidunit-testingrx-java2rx-kotlin2

Schedulers.io() Throwing NullPointerException in my Unit Tests


I'm trying to create unit tests for the method of my ViewModel below, which uses 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 **/
                }
            )
    )
}

But when Schedulers.io() is invoked in the test method, it throws a NullPointerException.

I've tried to use this approaches below:

https://medium.com/@dbottillo/how-to-unit-test-your-rxjava-code-in-kotlin-d239364687c9 (Creating a Rule)

https://medium.com/@PaulinaSadowska/writing-unit-tests-on-asynchronous-events-with-rxjava-and-rxkotlin-1616a27f69aa (Passing Schedulers to ViewModel)

In both approaches, it says to use Schedulers.trampoline() in test method. But it still throwing the error.

I'm running out of options, couldn't figure out why this happening.

Can someone help me?

Thanks.


Solution

  • From my experience, you got null because you have not mocked mRepository.doLogin. Try adding this at the beginning of your test function

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