简体   繁体   中英

How to mock and test RxJava/RxAndroid with Mockk?

I want to mock and test my Presenter with the Observable , but I don't know how to do that, the main part of the code as below:

//in my presenter:
override fun loadData(){
    this.disposable?.dispose()
    this.disposable = 
        Observable.create<List<Note>> {emitter->
            this.notesRepository.getNotes {notes->
                emitter.onNext(notes)
            }
        }
            .doOnSubscribe {
                this.view.showProgress()
            }
            .subscribe {
                this.view.hideProgress()
                this.view.displayNotes(it)
            }
}

//in test:
@Test
fun load_notes_from_repository_and_display(){
    val loadCallback = slot<(List<Note>)->Unit>();
    every {
        notesRepository.getNotes(capture(loadCallback))
    } answers {
        //Observable.just(FAKE_DATA)
        loadCallback.invoke(FAKE_DATA)
    }
    notesListPresenter.loadData()
    verifySequence {
        notesListView.showProgress()
        notesListView.hideProgress()
        notesListView.displayNotes(FAKE_DATA)
    }
}

I got the error: Verification failed: call 2 of 3: IView(#2).hideProgress()) was not called.

So, how to test the Rx things with Mockk in Android unit test? Thanks in advance!

Add the RxImmediateSchedulerRule from https://github.com/elye/demo_rxjava_manage_state , then Use spyk instead of mockk , and it works!

companion object
{
    @ClassRule @JvmField
    val schedulers = RxImmediateSchedulerRule()
}

@Test
fun load_notes_from_repository_and_display()
{
    val loadCallback = slot<(List<Note>)->Unit>();
    val notesRepo = spyk<INotesRepository>()
    val notesView = spyk<INotesListContract.IView>()
    every {
        notesRepo.getNotes(capture(loadCallback))
    } answers {
        loadCallback.invoke(FAKE_DATA)
    }

    val noteList = NotesListPresenter(notesRepo, notesView)
    noteList.loadData()

    verifySequence {
        notesView.showProgress()
        notesView.hideProgress()
        notesView.displayNotes(FAKE_DATA)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM