What and how to test in a Presenter with a RxAndro

2019-06-06 04:40发布

My project uses clean architecture.

I use:

  • MVP for the presentation layer
  • UseCases that use RxAndroid and get DisposableObservers
  • Dagger 2 for DI

Sample code from a presenter (Kotlin):

fun doSomething() {

    getInterestingDataUseCase.execute(object : DisposableObserver<List<InterestingDataItem>>() {

        override fun onStart() {
            view.showLoadingIndicator()
        }

        override fun onNext(dataList: List<InterestingDataItem>) {
            view.showDataItems(dataList)
        }

        override fun onError(e: Throwable) {
            view.showErrorDialog()
        }

        override fun onComplete() {
            view.hideLoadingIndicator()
        }
    })
}

I want to write unit tests for this presenter.

My question is: Are the different method calls in the DisposableObserver worth testing (onStart, onNext...)? And if they are, it looks like I would need to inject the DisposableObserver into the presenter(so that I will be able to mock it). Is there a cleaner way?

1条回答
爷、活的狠高调
2楼-- · 2019-06-06 05:13

Eventually I got to this solution:

  • Use Mockito to mock Objects and responses (as explained here)
  • Use Mockito Kotlin to be able to use an any() method that does not show compile time errors when used in Kotlin
  • Mock the behavior of the DisposableObserver when the UseCase's execute method is called

Example for a test that checks that the view hides its progress indicator when a request is complete:

@Test
fun stopsLoadingStateOnComplete() {

    //given
    given(getInterestingDataUseCase.execute(any())).
            will { invocation ->
                val observer = invocation.arguments[0] as DisposableObserver<List<InterestingDataItem>>
                observer.onComplete()
            }

    //when
    myPreseneter.onReady()

    //then
    then(view).should().hideLoadingIndicator()
}
查看更多
登录 后发表回答