Marcelo Hernandez
05/18/2019, 8:55 PMrunBlockingTest
, TestCoroutineDispatcher
, TestCoroutineScope
, etc. They look promising, however I haven't been able to figure out a way to stub a dependency's suspend
function using mockito-kotlin
such that it suspends indefinitely. The goal is to test scenarios within my Android ViewModel
where onCleared()
is called before a suspend
function returns a result. Basically something like:
private fun givenStatusNeverReceived() = runBlocking {
// loadStatus() is a suspend function
given(repository.loadStatus()).willAnswer {
// suspend indefinitely
}
}
louiscad
05/18/2019, 10:06 PMMarcelo Hernandez
05/18/2019, 10:20 PMmockito-kotlin
with a heavy focus on the BDDMockito APIs. I was hoping to maintain consistency moving forward, however with the recent introduction of coroutines in our codebase (we've been using RxJava heavily), it looks like mockito-kotlin
is starting to show its limitations.louiscad
05/18/2019, 10:29 PMMarcelo Hernandez
05/19/2019, 4:32 AMcoEvery
, coAnswer
, etc.
APIs make it quite easy to mock/stub suspend
functions.Marcelo Hernandez
05/19/2019, 4:39 AMmockito-kotlin
and got something working, but it looks rather ugly IMO. Basically it's something like:
private val deferredStatus = CompletableDeferred<Status>()
...
private fun TestCoroutineScope.whileAwaitingStatus() {
given(repository.loadStatus()).willAnswer {
var result: Status? = null
runBlockingTest {
result = deferredStatus.await()
}
return result!!
}
}
However, even if you choose to not set a value for the CompletableDeferred
, you have to make sure to call cancel()
on it otherwise runBlockingTest
throws an exception indicating that there was still an active Job
running.