'How to test async function in Mockk Kotlin
I want to test this function.
suspend fun fetchTwoDocs() =
coroutineScope {
val deferredOne = async { fetchDoc(1) }
val deferredTwo = async { fetchDoc(2) }
deferredOne.await()
deferredTwo.await()
}
How to test this function in mockk
Solution 1:[1]
I'm assuming you can't or won't rewrite the code you are writing to use coroutines. In that case, Pablisco offered great ideas here. The one I liked the best was using a queue:
// You create a sync queue
val queue = SynchronousQueue<String>() // Or the type of 'fetch2Docs'
// fetchTwoDocs runs async so it will return eventually
queue.put(fetchTwoDocs())
// queue.take() will wait until there is a value in the queue
assertThat(queue.take(), equalTo("expected value"))
Here an extra example on how to use this in an hypothetical async callback:
val queue = SynchronousQueue<String>()
asyncFunctionThatReturnsWithCallback(someParam) { callbackParam ->
queue.put(callbackParam)
}
assertTrue(queue.take())
Solution 2:[2]
If you just want to test the function, you can simply call it inside runBlocking
from your test, or use the kotlinx-coroutines-test library which provides runBlockingTest
:
@Test
fun test() = runBlocking {
val result = fetchTwoDocs()
// then assert stuff
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Joffrey |