https://kotlinlang.org logo
#android
Title
# android
m

matt tighe

09/06/2019, 8:46 PM
i’m having trouble unit testing a flow. i have a
ViewModel
that converts a flow from my DB into a livedata for the view layer. the VM extends coroutine scope.
Copy code
viewState.postValue(ViewState(loading = true))
this.launch {
    repository.observeAll().collect { observedList ->
        viewState.postValue(ViewState(list = observedList))
    }
}
and then in my test I’d like to do something like this:
Copy code
val expectedList = listOf(Thing())
coEvery { mockRepo.observeAll() } returns flow {
    emit(expectedList)
}

viewModel.submitAction(Action.Refresh)

coVerify {
    mockRepo.observeAll()
    mockViewStateObserver.onChanged(ViewState(loading = true, list = listOf()))
    mockViewStateObserver.onChanged(ViewState(loading = false, list = expectedList))
}
but the
coVerify
coroutine completes before the second update to the
LiveData
. anyone have suggestions besides injecting the test scope or delaying?
r

reline

09/06/2019, 9:06 PM
have you tried
runBlockingTest
from
kotlinx-coroutines-test
? It should ensure to run everything in
coVerify
before continuing.
m

matt tighe

09/06/2019, 9:16 PM
that totally does the trick. thanks
👍 1
3 Views