Android 如何测试rxjava链接?
您好,我创建了一个实现,它使用flatmap将两个请求链接在一起,最终结果是从第二个请求返回一个响应对象,我想知道是否可以模拟这两个链接的响应对象 这是主要代码Android 如何测试rxjava链接?,android,unit-testing,kotlin,rx-java2,Android,Unit Testing,Kotlin,Rx Java2,您好,我创建了一个实现,它使用flatmap将两个请求链接在一起,最终结果是从第二个请求返回一个响应对象,我想知道是否可以模拟这两个链接的响应对象 这是主要代码 delegator.requestOne(requestData) .flatMap ({ response -> if(response.isSuccessful){ cookieStorage.saveSe
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.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(...)
然后,您可以测试来自该链的“输出”(发出的项)是否是您期望的,例如,使用a,或者在您的示例中,使用您期望/已模拟的响应调用回调
Rx链将在您的测试中运行,与“正常”运行代码时完全相同
您不能模拟Rx链的行为,例如,您不能模拟flatMap{}
的运行方式
Mockito.when(delegator.requestOne(...)).thenReturn(...)
Mockito.when(delegator.requestTwo(...)).thenReturn(...) / Mockito.when(delegator.requestTwo(responseOne)).thenReturn(...)