【问题标题】:How to test rxjava chaining?如何测试 rxjava 链接?
【发布时间】:2018-06-20 18:12:44
【问题描述】:

您好,我创建了使用 flatmap 将两个请求链接在一起的实现,最终结果是从第二个请求返回的响应对象,并且想知道是否可以模拟这两个链接的响应对象?

这里是主要代码

delegator.requestOne(requestData)
                .flatMap ({  response ->
                    if(response.isSuccessful){
                        cookieStorage.saveSessionCookies(response.header(cookieStorage.COOKIE_HEADER_NAME)!!)
                    }
                    delegator.requestTwo

                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(object : SingleObserver<ResponseTwo>() {
                    @Override
                    fun onSubscribe(Disposable d) {
                    }

                    @Override
                    fun onSuccess(responseTwo :ResponseTwo) {
                        callback.onSuccess(responseTwo)
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });

如果这没有平面图并且只处理一个请求/响应,我将使用 mockito 编写以下内容

Mockito.when(network.makeReq()).thenReturn(Single.just(responseOne));

但是我该怎么做这样的事情:

Mockito.when(foodHygieneController.getLocalAuthorities()).thenReturn(Single.just(requestOne)).thenReturn(requestTwo)??

假设 requestOne 和 RequestTwo 是我选择的硬编码模拟值

【问题讨论】:

    标签: android unit-testing kotlin rx-java2


    【解决方案1】:

    您只需模拟 Rx 链中的每个请求(调用模拟对象)。 在你的情况下:

    Mockito.when(delegator.requestOne(...)).thenReturn(...)
    Mockito.when(delegator.requestTwo(...)).thenReturn(...) / Mockito.when(delegator.requestTwo(responseOne)).thenReturn(...)
    

    然后您可以测试该链中的“输出”(发出的项目)是否符合您的预期,例如使用TestSubscriber,或者在您的示例中,使用@987654324 调用callback @你期望/嘲笑过。

    Rx 链将在您的测试中完全按照“正常”运行代码时的方式运行。

    你不能做的是模拟 Rx 链的行为,例如你不能嘲笑flatMap{} 的运作方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多