Coroutines
Mokkery supports suspendable functions out of the box, making it easy to mock them right away with the core answers.
everySuspend { mock.fetchAt(any()) } calls { (index: Int) ->
delay(1_000)
index + 1
}
Coroutine utils module
Starting with Mokkery 2.2.0, the mokkery-coroutines module is available, featuring kotlinx-coroutines specific answers.
Setup
Add dev.mokkery:mokkery-coroutines:$version to your dependencies:
dependencies {
implementation("dev.mokkery:mokkery-coroutines:$version")
}
Alternatively, use the mokkery(module: String) utility from the Mokkery Gradle plugin for easier setup:
import dev.mokkery.gradle.mokkery
dependencies {
implementation(mokkery("coroutines")) // defaults to the current Mokkery version
}
Awaits API
To await a Deferred, use awaits overload:
val deferred = CompletableDeferred<Int>()
everySuspend { mock.fetchAt(any()) } awaits deferred
Deferred might be created on each call:
everySuspend { mock.fetchAt(any()) } awaits { (index: Int) -> createDeferred(index) }
To await multiple
Deferred instances and return results as a List, use all:
import dev.mokkery.coroutines.answering.Awaitable.Companion.all
val deferred1 = CompletableDeferred<Int>()
val deferred2 = CompletableDeferred<Int>()
val deferred3 = CompletableDeferred<Int>()
everySuspend { mock.fetchAll() } awaits all(deferred1, deferred2, deferred3)
To suspend indefinitely until coroutine is canceled, use awaits cancellation:
import dev.mokkery.coroutines.answering.Awaitable.Companion.cancellation
everySuspend { mock.fetchAll() } awaits cancellation
To await an element from a
Channel, use awaits receive(...):
import dev.mokkery.coroutines.answering.Awaitable.Companion.receive
val channel = Channel<List<Int>>()
everySuspend { mock.fetchAll() } awaits receive(from = channel)
For Unit-returning functions, you can use awaits send(...) to send an element to
a Channel.
import dev.mokkery.coroutines.answering.Awaitable.Companion.send
val channel = Channel<Int>()
everySuspend { mock.insert(any()) } awaits send(to = channel) { it.arg(0) }
To return a value after a delay, use awaits delayed(...):
import dev.mokkery.coroutines.answering.Awaitable.Companion.delayed
everySuspend { mock.fetchAt(any()) } awaits delayed(value = 10) // by default, the delay takes 1 second.
The delayed also accepts a lambda:
import dev.mokkery.coroutines.answering.Awaitable.Companion.delayed
everySuspend { mock.fetchAt(any()) } awaits delayed(by = 2.seconds) { (index: Int) -> index + 1 }