Adrian Coman
Adrian Coman

Reputation: 1536

Unit test for server polling using RxJava, Kotlin

I'm trying to create a test using JUnit and Mockito for the following scenario: make a call to the server, in case the response is not successful, retry the request.

repository.uploadModel(model)
                .subscribeOn(schedulers.io())
                .observeOn(schedulers.ui())
                .repeatWhen (repeatTimer)
                .subscribe({
                    if (it.isSuccessful) {
                        mvpView?.showUploadComplete()
                    } else {
                        mvpView?.showGeneralUploadError()
                    }
                }, {
                     it.printStackTrace()
                })

So far I came up with this:

val model = Mockito.mock(Model::class.java)
val errorResponse = Response.error<Any>(500, ResponseBody.create(null, ""))

whenever(repository.uploadModel(model))           
    .thenReturn(Flowable.just(errorResponse))

presenter?.uploadModel()
testScheduler?.triggerActions()

verify(view, atLeast(5)).pendingUpload()

What actually happens: showGeneralUploadError() is called only once and then the test ends and fails. What I want to happen: call showGeneralUploadError() multiple times

Extra info:

  1. repeatTimer is defined as { it: Flowable<Any> -> it.delay(0, TimeUnit.SECONDS)} for unit testing
  2. repeatTimer is defined as { it: Flowable<Any> -> it.delay(5, TimeUnit.SECONDS)} for production
  3. This is only sample code to demonstrate the problem, not actual code

Upvotes: 0

Views: 623

Answers (2)

Adrian Coman
Adrian Coman

Reputation: 1536

The problem was at repeatTimer. I tried to declare it for mocking purposes as:

repeatTimer is defined as { it: Flowable<Any> -> it.delay(0, TimeUnit.SECONDS)}

but it should have been just

{ it: Flowable<Any> -> it}

Upvotes: 0

Bob Dalgleish
Bob Dalgleish

Reputation: 8227

The takeUntil() operator would only respond to data emitted via onNext(). Since your test never emits a data value, there is nothing for it to do.

It's not clear from your sample code what you are trying to accomplish, so I can't suggest what you can do to fix this.

Upvotes: 2

Related Questions