我想编写一个单元测试,将在下面验证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)

  }

最佳答案

您在whenever语句之一中有错字:
whenever(deviceUtil.apiVersion()).thenReturn("apiversion")
您已经指示要返回“apiversion”,但是实际的request是用另一种方式声明的:
val request = RequestInit(..., ..., "osversion")
这两个字符串的不等于,因此Mockito无法返回您期望的Observable

"osversion"更改为"apiversion"

10-04 11:42