gpt4 book ai didi

android - 如何测试 rxjava 链接?

转载 作者:太空狗 更新时间:2023-10-29 13:05:51 27 4
gpt4 key购买 nike

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

这是主要代码

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 是我选择的硬编码模拟值

最佳答案

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

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

然后您可以测试该链的“输出”(发出的项目)是否符合您的预期,例如 TestSubscriber ,或者在您的示例中,该 callback 是使用您期望/已经模拟的 ResponseTwo 调用的。

Rx 链将在您的测试中运行,就像它在“正常”运行代码时一样。

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

关于android - 如何测试 rxjava 链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48206658/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com