2

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.

1 Answers1

2

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(...)
Bach Vu
  • 2,298
  • 1
  • 15
  • 19
  • Thanks for replying. But I've mocked with `Mockito.`when`(mRepository.doLogin("", "")).thenReturn(Single.just(""))` – Tiago Almeida Oct 22 '19 at 21:13
  • Oh, I've found the problem. You were right, I was mocking the mRepository.doLogin wrong. – Tiago Almeida Oct 22 '19 at 21:21
  • Just for clarification: In the posted code above has a method called createJsonArray. If the parameters of the mRepository.doLogin are empty, it creates a "[]" String. So instead of mocking the two paremeters with "", I needed to pass the second parameter as "[]". Something like this `Mockito.when(mRepository.doLogin("", "[]")).thenReturn(Single.just(""))` and it works. – Tiago Almeida Oct 22 '19 at 21:25
  • Glad I could help :) – Bach Vu Oct 22 '19 at 22:24
  • @TiagoAlmeida Learn to read stacktraces, it's easy and it will save you a lot of time. – m0skit0 Oct 23 '19 at 19:23
  • Hi bach , i faced with this problem and i added `Momckito.when` before please check my question in https://stackoverflow.com/questions/64192492/test-junit-rxjava-method – milad salimi Oct 04 '20 at 09:18