Skip to main content

Coroutines

Mokkery supports suspendable functions out of the box, making it easy to mock them right away with the core answers.

everySuspend { repository.findById(any()) } calls { (id: String) ->
delay(1_000)
Book(id = id)
}

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<Book>()
everySuspend { repository.findById("1") } awaits deferred

Deferred might be created on each call:

everySuspend { repository.findById(any()) } awaits { (id: String) -> createBookDeferred(id) }

To await multiple Deferred instances and return results as a List, use all:

import dev.mokkery.coroutines.answering.Awaitable.Companion.all

val deferred1 = CompletableDeferred<Book>()
val deferred2 = CompletableDeferred<Book>()
val deferred3 = CompletableDeferred<Book>()

everySuspend { repository.findAll() } awaits all(deferred1, deferred2, deferred3)

To suspend indefinitely until coroutine is canceled, use awaits cancellation:

import dev.mokkery.coroutines.answering.Awaitable.Companion.cancellation

everySuspend { repository.findById(any()) } awaits cancellation

To await an element from a Channel, use awaits receive(...):

import dev.mokkery.coroutines.answering.Awaitable.Companion.receive

val channel = Channel<Book>()

everySuspend { repository.findById(any()) } 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<String>()

everySuspend { repository.deleteById(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 { repository.findById(any()) } awaits delayed(value = Book(...)) // by default, the delay takes 1 second.

The delayed also accepts a lambda:

import dev.mokkery.coroutines.answering.Awaitable.Companion.delayed

everySuspend { repository.findById(any()) } awaits delayed(by = 2.seconds) { (id: String) -> Book(id = id) }