在RxAndroid用例的演示者中测试什么以及如何测试
我的项目使用干净的架构 。
我用:
- 表示层的MVP
- 使用使用RxAndroid并获得DisposableObservers的案例
- DI的匕首2
来自演示者(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() } }) }
我想为这个主持人编写单元测试。
我的问题是:在DisposableObserver不同的方法调用值得测试(onStart,onNext …)? 如果是这样的话,看起来好像我需要将DisposableObserver注入主持人(这样我就可以嘲笑它)。 有更清洁的方法吗?
最终我得到了这个解决方案:
- 使用Mockito模拟对象和响应(如这里所解释的)
- 使用Mockito Kotlin可以使用任何()方法,在Kotlin中不显示编译时错误
- 在调用UseCase的execute方法时,模拟DisposableObserver的行为
在请求完成时检查视图隐藏其进度指示器的测试示例:
@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() }