您好我已经创建了使用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) {
}
});
如果没有flatmap并且只处理一个请求/响应,我会使用mockito编写以下内容
Mockito.when(network.makeReq()).thenReturn(Single.just(responseOne));
但我怎么能这样做:
Mockito.when(foodHygieneController.getLocalAuthorities()).thenReturn(Single.just(requestOne)).thenReturn(requestTwo)??
假设requestOne和RequestTwo是我选择的硬编码模拟值
答案 0 :(得分:2)
您只需模拟作为Rx链一部分的每个请求(调用模拟对象)。 在你的情况下:
Mockito.when(delegator.requestOne(...)).thenReturn(...)
Mockito.when(delegator.requestTwo(...)).thenReturn(...) / Mockito.when(delegator.requestTwo(responseOne)).thenReturn(...)
然后,您可以测试该链中的“输出”(发出的项目)是您期望的那样,例如使用TestSubscriber,或者在您的示例中,callback
被调用使用您期望/已经嘲笑的ResponseTwo
。
Rx链将在您的测试中完全按照“正常”运行代码的方式运行。
你不能做的是嘲笑Rx链的行为,例如:你无法模仿flatMap{}
的运作方式。