本文介绍了如何对“repeatWhen"进行单元测试在 RxJava 服务器轮询中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码
return Observable.defer(() -> mApi.verifyReceipt(username, password))
.subscribeOn(Schedulers.io())
.doOnNext(this::errorCheck)
.repeatWhen(observable -> observable.delay(1, TimeUnit.SECONDS))
.takeUntil(Response::body)
.filter(Response::body)
.map(Response::body);
它继续轮询并接收false"布尔响应,并在接收到true"时停止轮询.我为 onNext() 案例制作了一个测试案例,例如:
It keeps polling and receives a "false" boolean response and stops polling when "true" is received. I've made a test case for the onNext() case like:
@Test
public void testVerifyReceiptSuccessTrueResponse() {
Response<Boolean> successTrueResponse = Response.success(Boolean.TRUE);
when(mMockApi.verifyReceipt(any(), any())).thenReturn(Observable.just(successTrueResponse));
mService.verifyReceipt("", "").subscribe(mMockVerifyReceiptSubscriber);
verify(mMockVerifyReceiptSubscriber).onNext(eq(Boolean.TRUE));
}
如果响应为false",则在继续轮询时如何测试情况有什么建议?
Any suggestion on how to test the situation when it keeps on polling if the response is "false"?
推荐答案
when(mMockApi.verifyReceipt(any(), any()))
.thenReturn(Observable.just(successFalseResponse))
.thenReturn(Observable.just(successTrueResponse));
Observable observable = mService.verifyReceipt("", "");
observable.subscribe(mMockVerifyReceiptSubscriber);
// Two approaches here
// First one - sleep as much as specified in delay(), in your case 1 second
// and then perform verification specified on next line
// Second approach (better) - make your architecture in a way, that you can
// provide an implementation to `repeatWhen()` operator, in other words,
// inject. And then you'll be able to inject `observable.delay(1, TimeUnit.SECONDS)`
// for production code and inject retry logic without delay for test code.
// Now we are verifying that because of first time `false` was returned,
// then retryWhen() logics are performed
verify(observable).delay(1, TimeUnit.SECONDS); // here should be the injected implementation
verify(mMockVerifyReceiptSubscriber).onNext(eq(Boolean.TRUE));
现在,第一次 observable 将发出 false
这将调用您的 retryWhen()
,下次将发出 true
.
Now, first time observable will emit false
which will call your retryWhen()
, next time true
will be emitted.
这篇关于如何对“repeatWhen"进行单元测试在 RxJava 服务器轮询中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!