When using kotlin coroutines, how do I unit test a function that calls a suspend function?

Fixing async

As implemented, your someFun() will just “fire and forget” the async result. As a result, runBlocking does not make a difference in that test.

If possible, make someFun() return async‘s Deferred and then, in runBlocking, call await on it.

fun someFun(): Deferred<Unit> {
    // ... Some synchronous code
    return async {
        suspendFun()
    }
}

Then the test:

runBlocking {
    SomeClass().someFun().await()
}

This question/answer is a good resource for further information.

alternative: use launch

It’s also possible to avoid async in favor of using suspend functions and a launch-created coroutine:

suspend fun someFun() {
    // ... Some synchronous code
    suspendFun()
}

private suspend fun suspendFun() {
    delay(1000)
    println("executed")
    // ... other code
}

The test uses launch and the outer runBlocking implicitly waits for its completion:

val myScope = GlobalScope
runBlocking {
    myScope.launch {
        SomeClass().someFun()
    }
}

Leave a Comment

tech