2

我想用 来模拟和测试我PresenterObservable,但我不知道该怎么做,代码的主要部分如下:

//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 的东西呢?提前致谢!

4

1 回答 1

5

添加RxImmediateSchedulerRule来自https://github.com/elye/demo_rxjava_manage_state,然后使用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)
    }
}
于 2018-07-03T09:27:03.983 回答