How to unit test “repeatWhen” in RxJava server polling

爷,独闯天下 提交于 2021-01-28 05:41:43

问题


This is my code

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);

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));
}

Any suggestion on how to test the situation when it keeps on polling if the response is "false"?


回答1:


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));

Now, first time observable will emit false which will call your retryWhen(), next time true will be emitted.



来源:https://stackoverflow.com/questions/43543287/how-to-unit-test-repeatwhen-in-rxjava-server-polling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!