How to mock and test RxJava/RxAndroid with Mockk?


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:


Presenter


Observable


//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.


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!





Not sure I understand. If it is a bug, then just please submit github issue here: github.com/mockk/mockk/issues/new otherwise lets just wait some people with RxJava experience appear.
– oleksiyp
Jun 25 at 17:06





I fixed it with spky instead of mockk, thanks!
– SpkingR
Jul 3 at 9:25


spky


mockk




1 Answer
1



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


RxImmediateSchedulerRule


spyk


mockk


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)
}
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages