TestScheduler不起作用(Kotlin + RxJava2 + mockito)

时间:2017-11-30 14:51:30

标签: android unit-testing kotlin mockito rx-java2

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

  }

1 个答案:

答案 0 :(得分:2)

您在其中一个whenever语句中输入了拼写错误:


    whenever(deviceUtil.apiVersion()).thenReturn("apiversion")

您已指示返回“apiversion”,但实际的request以另一种方式声明:


    val request = RequestInit(..., ..., "osversion")

这两个字符串相等,因此Mockito无法返回您期望的Observable

"osversion"更改为"apiversion"