我想用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)
}
}
我得到了错误:
Verification failed: call 2 of 3: IView(#2).hideProgress()) was not called.
那么,如何在Android单元测试中使用Mockk测试Rx呢?预先感谢!
答案 0 :(得分:1)
从https://github.com/elye/demo_rxjava_manage_state中添加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)
}
}