Unit test for server polling using RxJava, Kotlin - android

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

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.

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}

Related

Kotlin Flow not collected anymore after working initially

Basically I want to make a network request when initiated by the user, collect the Flow returned by the repository and run some code depending on the result. My current setup looks like this:
Viewmodel
private val _requestResult = MutableSharedFlow<Result<Data>>()
val requestResult = _requestResult.filterNotNull().shareIn(
scope = viewModelScope,
started = SharingStarted.WhileViewSubscribed,
replay = 0
)
fun makeRequest() {
viewModelScope.launch {
repository.makeRequest().collect { _requestResult.emit(it) }
}
}
Fragment
buttonLayout.listener = object : BottomButtonLayout.Listener {
override fun onButtonClick() {
viewModel.makeRequest()
}
}
lifecycleScope.launchWhenCreated {
viewModel.requestResult.collect { result ->
when (result) {
Result.Loading -> {
doStuff()
}
is Result.Success -> {
doDifferentStuff(result.data)
}
is Result.Failure -> {
handleError()
}
}
}
}
The first time the request is made everything seems to work. But starting with the second time the collect block in the fragment does not run anymore. The request is still made, the repository returns the flow as expected, the collect block in the viewmodel runs and emit() also seems to be executed successfully.
So what could be the problem here? Something about the coroutine scopes? Admittedly I lack any sort of deeper understanding of the matter at hand.
Also is there a more efficient way of accomplishing what I'm attempting using Kotlin Flows in general? Collecting a flow and then emitting the same flow again seems a bit counterintuitive.
Thanks in advance:)
According to the documentation there are two recommended alternatives:
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
//your thing
}
}
I rather the other alternative:
viewLifecycleOwner.lifecycleScope.launch {
viewModel.makeReques().flowWithLifecycle(viewLifecycleOwner.lifecycle, Lifecycle.State.STARTED)
.collect {
// Process the value.
}
}
I like the flowWithLifecycle shorter syntax and less boiler plate. Be carefull thar is bloking so you cant have anything after that.
The oficial docs
https://developer.android.com/topic/libraries/architecture/coroutines
Please be aware you need the lifecycle aware library.

Unit Test for RxJava and Retrofit

I have This method that calls a Rest API and returns the result as an Observable (Single):
fun resetPassword(email: String): Single<ResetPassword> {
return Single.create { emitter ->
val subscription = mApiInterfacePanda.resetPassword(email)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ resetPasswordResponse ->
when(resetPasswordResponse.code()) {
200 -> {
resetPasswordResponse?.body()?.let { resetPassword ->
emitter.onSuccess(resetPassword)
}
}
else -> emitter.onError(Exception("Server Error"))
}
}, { throwable ->
emitter.onError(throwable)
})
mCompositeDisposable.add(subscription)
}
}
Unit Test:
#Test
fun resetPassword_200() {
val response = Response.success(200, sMockResetPasswordResponse)
Mockito.`when`(mApiInterfacePanda.resetPassword(Mockito.anyString()))
.thenReturn(Single.just(response))
mTokenRepository.resetPassword(MOCK_EMAIL)
val observer = mApiInterfacePanda.resetPassword(MOCK_EMAIL)
val testObserver = TestObserver.create<Response<ResetPassword>>()
observer.subscribe(testObserver)
testObserver.assertSubscribed()
testObserver.awaitCount(1)
testObserver.assertComplete()
testObserver.assertResult(response)
}
My Problem is only this line gets covered and the other lines won't run and that has a lot of impact on my total test coverage:
return Single.create { emitter ->
There's more than one thing going on here if I'm not mistaken. Let's take it in parts.
First, your "internal" observer:
mApiInterfacePanda.resetPassword(email)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ resetPasswordResponse -> ... })
Is observing on the android main thread and executing on a background thread. To the best of my knowledge, in most cases, the test thread will end before your mApiInterfacePanda .resetPassword has a chance to finish and run. You didn't really post the test setup, so I'm not sure if this is an actual issue, but in any case it's worth mentioning. Here's 2 ways to fix this:
RxJavaPlugins and RxAndroidPlugins
RxJava already provides a way to change the schedulers that are provided. An example is RxAndroidPlugins.setMainThreadSchedulerHandler. Here's how it could help:
#Before
fun setUp() {
RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() }
RxJavaPlugins.setInitIoSchedulerHandler { Schedulers.trampoline() }
}
The above methods make sure that everywhere you use the main thread scheduler and the io scheduler, it'll instead return the trampoline scheduler. This is a scheduler that guarantees that the code is executed in the same thread that was executing previously. In other words, it'll make sure you run it on the unit test main thread.
You will have to undo these:
#After
fun tearDown() {
RxAndroidPlugins.reset()
RxJavaPlugins.reset()
}
You can also change other schedulers.
Inject the schedulers
You can use kotlin's default arguments to help out with injecting schedulers:
fun resetPassword(
email: String,
obsScheduler: Scheduler = AndroidSchedulers.mainThread(),
subScheduler: Scheduler = Schedulers.io()
): Single<ResetPassword> {
return Single.create { emitter ->
val subscription = mApiInterfacePanda.resetPassword(email)
.observeOn(obsScheduler)
.subscribeOn(subScheduler)
.subscribe({ resetPasswordResponse ->
when(resetPasswordResponse.code()) {
200 -> {
resetPasswordResponse?.body()?.let { resetPassword ->
emitter.onSuccess(resetPassword)
}
}
else -> emitter.onError(Exception("Server Error"))
}
}, { throwable ->
emitter.onError(throwable)
})
mCompositeDisposable.add(subscription)
}
}
At test time you can just call it like resetPassword("foo#bar.com", Schedulers.trampoline(), Schedulers.trampoline() and for the application just pass in the email.
The other thing I see here is maybe not related to the problem, but I think it's still good to know. First, you're creating a single, but you don't need to do this.
Single.create is usually used when you don't have reactive code. However, mApiInterfacePanda.resetPassword(email) already returns a reactive component and although I'm not sure, let's just assume it's a single. If not, it should be fairly simple to convert it to something else.
You're also holding on to a disposable, which from what I can tell shouldn't be necessary.
Lastly, you're using retrofit according to your tags so you don't need to make the call return a raw response unless extremely necessary. This is true because retrofit checks the status code for you and will deliver the errors inside onError with an http exception. This is the Rx way of handling the errors.
With all this in mind, I'd rewrite the entire method like this:
fun resetPassword(email: String) = mApiInterfacePanda.resetPassword(email)
(note that resetPassword must not return a raw response, but Single<ResetPassword>
It actually shouldn't need anything else. Retrofit will make sure things end up in either onSuccess or onError. You don't need to subscribe to the result of the api here and handle disposables - let whoever is calling this code handle it.
You may also notice that if this is the case, then the solution for the schedulers is not needed. I guess this is true in this case, just remember some operators operate in some default schedulers and you may need to override them in some cases.
So how would I test the above method?
Personally I'd just check if the method calls the api with the right parameters:
#Test
fun resetPassword() {
mTokenRepository.resetPassword(MOCK_EMAIL)
verify(mApiInterfacePanda).resetPassword(MOCK_EMAIL)
}
I don't think there's much more needed here. There's no more logic I can see in the rewritten method.

RxJava unit testing - Observable not emitting events in tests

I'm testing a view model which has the following definition:
class PostViewModel(private val postApi: PostApi): ViewModel() {
private val _post: PublishSubject<Post> = PublishSubject.create()
val postAuthor: Observable<String> = _post.map { it.author }
fun refresh(): Completable {
return postApi.getPost() // returns Single<Post>
.doOnSuccess {
_post.onNext(it)
}
.ignoreElement()
}
}
}
My fragment then displays the post author by subscribing to viewModel.postAuthor in its onActivityCreated and calling and subscribing to refresh() whenever the user wants an updated post and everything is fine and dandy.
The issue I'm running into is trying to verify this behaviour in a unit test: specifically, I am unable to get postAuthor to emit an event in my testing environment.
My test is defined as follows:
#Test
fun `When view model is successfully refreshed, display postAuthor`() {
val post = Post(...)
whenever(mockPostApi.getPost().thenReturn(Single.just(post))
viewModel.refresh()
.andThen(viewModel.postAuthor)
.test()
.assertValue { it == "George Orwell" }
}
The test fails due to no values or errors being emitted, even though I can verify through the debugger that the mock does in-fact return the Post as expected. Is there something obvious that I'm missing, or am I completely wrong in my testing approach?
viewModel.postAuthor is a hot-observable. It emits value when you call _post.onNext(it).
Unlike a cold-observable, the late subscribers cannot receive the values that got emitted before they subscribe.
So in your case I think the viewModel.postAuthor is subscribed after you call viewModel.refresh(), so it cannot receive the value.
The observable could be emitting on a different thread so that's why it's empty when the test is checking the values/errors.
You could try forcing your observable to emit on the same thread. Depending on which scheduler you're using, it'd be something like:
RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }

Kotlin coroutines using produces and mockito to mock the producing job

I am testing Kotlin coroutines in my Android app and I am trying to do the following unit test
#Test fun `When getVenues success calls explore venues net controller and forwards result to listener`() =
runBlocking {
val near = "Barcelona"
val result = buildMockVenues()
val producerJob = produce<List<VenueModel>>(coroutineContext) { result.value }
whenever(venuesRepository.getVenues(eq(near))) doReturn producerJob // produce corooutine called inside interactor.getVenues(..)
interactor.getVenues(near, success, error) // call to real method
verify(venuesRepository).getVenues(eq(near))
verify(success).invoke(argThat {
value == result.value
})
}
The interactor method is as follows
fun getVenues(near: String, success: Callback<GetVenuesResult>,
error: Callback<GetVenuesResult>) =
postExecute {
repository.getVenues(near).consumeEach { venues ->
if (venues.isEmpty()) {
error(GetVenuesResult(venues, Throwable("No venues where found")))
} else {
success(GetVenuesResult(venues))
}
}
}
postExecute{..} is a method on a BaseInteractor that executes the function in the ui thread through a custom Executor that uses the launch(UI) coroutine from kotlin android coroutines library
fun <T> postExecute(uiFun: suspend () -> T) =
executor.ui(uiFun)
Then the repository.getVenues(..) function is also a coroutine that returns the ProducerJob using produce(CommonPool) {}
The problem is that it seams that success callback in the interactor function doesn't seem to be executed as per the
verify(success).invoke(argThat {
value == result.value
})
However, I do see while debugging that the execution in the interactor function reaches to the if (venues.isEmpty()) line inside the consumeEach but then from there exits and continues with the test, obviously failing on the verify for the success callback.
I am a bit new on coroutines so any help would be appreciated.
I figured this one out. I saw that the problem was just with this producing coroutine and not with the others tests that are also using coroutines and working just fine. I noticed that I actually missed the send on the mocked ProducingJob in order to have it actually produce a value, in this case the list of mocks. I just added that changing the mock of the producing job to
val producerJob = produce { send(result.value) }

Testing RxJava infinite interval

I have a simple view that displays currencies as list. App fetches currencies from web service every 1 second. So I have following method in my ViewModel:
fun onViewAppeared() {
currenciesViewStateUpdates.onNext(CurrenciesViewState(true, null))
Flowable.interval(1, TimeUnit.SECONDS)
.flatMapSingle { _ -> currenciesService.calculateCurrencies(Currency("EUR", 10.0)) }
.doOnError { error -> Log.d("LOG", error.message) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe { currencies ->
currenciesViewStateUpdates.onNext(CurrenciesViewState(false, currencies))
}
}
Now I need to unit test this behavior:
#Test
fun viewAppearedAndCurrenciesRequestSucceeded_currenciesDisplayed() {
val currencies = listOf(Currency("", 0.0))
Mockito.`when`(currenciesServiceMock.calculateCurrencies(anyCurrency())).thenReturn(Single.just(currencies))
viewModel.getViewStateUpdates().subscribe(testObserver)
viewModel.onViewAppeared()
testObserver.assertSubscribed()
testObserver.assertNoErrors()
testObserver.assertValueCount(2)
assertFalse(testObserver.values()[1].loading)
assertNotNull(testObserver.values()[1].currencies)
testObserver.values()[1].currencies?.let { assertTrue(it.isNotEmpty()) }
}
All RxSchedulers set up for immediate. Problem: with test awaits forever when observable finishes subscription, but it will never finish cause it is infinite interval. How can I test it?
You will have problems running your tests in the way that you have fashioned.
Make your schedulers into class parameters, so that they can be injected in the proper fashion, both during testing and production.
Use test schedulers instead of Schedulers.immediate() because you can end up in a deadlock.
Always have your timed operations (interval(), timeout(), etc) operate on explicit schedulers, usually ones that you have injected.

Categories

Resources