簡體   English   中英

如何在 Mockk Kotlin 中測試異步 function

[英]How to test async function in Mockk Kotlin

我想測試這個function。

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

如何在 mockk 中測試這個 function

我假設您不能或不會重寫您正在編寫的代碼以使用協程 在這種情況下,Pablisco 在這里提出了很好的想法 我最喜歡的一個是使用隊列:

// 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"))

這是一個關於如何在假設的異步回調中使用它的額外示例:

val queue = SynchronousQueue<String>()
asyncFunctionThatReturnsWithCallback(someParam) { callbackParam ->
    queue.put(callbackParam)
}
assertTrue(queue.take())

如果你只是想測試這個函數,你可以簡單地從你的測試中在runBlocking調用它,或者使用提供runBlockingTestkotlinx-coroutines-test庫:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM