首页 > 解决方案 > 如何在 Mockk Kotlin 中测试异步功能

问题描述

我想测试这个功能。

suspend fun fetchTwoDocs() =
        coroutineScope {
            val deferredOne = async { fetchDoc(1) }
            val deferredTwo = async { fetchDoc(2) }
            deferredOne.await()
            deferredTwo.await()
        }

如何在 mockk 中测试此功能

标签: androidkotlinmockkmockk-verify

解决方案


如果你只是想测试这个函数,你可以简单地runBlocking从你的测试中调用它,或者使用kotlinx-coroutines-test库,它提供runBlockingTest

@Test
fun test() = runBlocking {
    val result = fetchTwoDocs()
    // then assert stuff
}

推荐阅读