我想编写一个单元测试来验证下面的callInit
方法。但是,我有空指针异常,其中行保持subscribe(
。我的问题是如何在下面的方法中验证onnext和onerror条件?
override fun callInit() {
val requestInit = RequestInit(os = "android", osVersion = deviceUtil.osVersion(),
appVersion = deviceUtil.apiVersion())
compositeDisposable.add(
interactor.getInit(requestInit)
.subscribe(
{
view.hideProgress()
this.commercialLink = it.commercialLink
view.updateScreen()
},
{ error -> view.onError(error) }
)
)
}
测试方法:
@Test
fun should_update_commerciallink_AND_updateScreen_when_callInit() {
val request = RequestInit("android", "version", "osversion")
val responseInit = ResponseInit(false, false,
"updatelink", "message", "useragreement", "commerciallink")
whenever(deviceUtil.osVersion()).thenReturn("version")
whenever(deviceUtil.apiVersion()).thenReturn("apiversion")
whenever(interactor.getInit(request)).thenReturn(Observable.just(responseInit))
presenter.callInit()
testScheduler.triggerActions()
verify(view).hideProgress()
verify(view).updateScreen()
}
修改
class SplashInteractor(private val initService: InitService,
private val schedulerProvider: SchedulerProvider) : SplashContract.Interactor {
override fun getInit(requestInit: SplashRequest.Init): Observable<SplashResponse.Init> {
return initService.init(requestInit)
.subscribeOn(schedulerProvider.io())
.flatMap(funcErrorCheckAndTransform())
.flatMap(funcVersionControl())
.observeOn(schedulerProvider.ui())
}
override fun downloadCommercialVideo(commercialLink: String): Observable<File> {
return initService.downloadCommercialLink(commercialLink)
.subscribeOn(schedulerProvider.io())
.flatMap(funcDownload(commercialLink))
.observeOn(schedulerProvider.ui())
}
}
演示者测试
@Before
fun setUp() {
testScheduler = TestScheduler()
interactor = SplashInteractor(initService, TestSchedulerProvider(testScheduler))
presenter = SplashPresenter(contract, interactor, uriWrapper, compositeDisposable,
cache, fileUtil, deviceUtil)
spyPresenter = Mockito.spy(presenter)
}
答案 0 :(得分:2)
您在其中一个whenever
语句中输入了拼写错误:
whenever(deviceUtil.apiVersion()).thenReturn("apiversion")
您已指示返回“apiversion”,但实际的request
以另一种方式声明:
val request = RequestInit(..., ..., "osversion")
这两个字符串不相等,因此Mockito无法返回您期望的Observable
。
将"osversion"
更改为"apiversion"
。