When testing coroutines, I'd like to be able to mock a dependency with a suspend function with a custom Answer such that it delays, suspends indefinitely, or has other custom behavior besides simply returning a value. The particular test case I have in mind is testing that when the CoroutineScope of the class under test gets cancelled while one of its dependencies is suspending, it properly cancels the dependency and avoids further execution.
Example:
runBlocking {
whenever(repository.loadStatus()).willAnswer {
// Suspend indefinitely
suspendCancellableCoroutine<Status> {} <-- Compiler error 'Suspension functions can be called only within coroutine body'
}
}
or
mock<Repository> {
onBlocking {
loadStatus()
} doAnswer {
// Suspend indefinitely
suspendCancellableCoroutine {} <-- Compiler error 'Suspension functions can be called only within coroutine body'
}
}
MockK currently supports something like this with:
When testing coroutines, I'd like to be able to mock a dependency with a
suspend
function with a customAnswer
such that it delays, suspends indefinitely, or has other custom behavior besides simply returning a value. The particular test case I have in mind is testing that when theCoroutineScope
of the class under test gets cancelled while one of its dependencies is suspending, it properly cancels the dependency and avoids further execution.Example:
or
MockK currently supports something like this with:
Testing asynchronous coroutines code is now achievable with the latest version of https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/.