gpt4 book ai didi

unit-testing - 暂停可取消协程取消的 Kotlin Mockk 测试

转载 作者:行者123 更新时间:2023-12-02 13:43:48 25 4
gpt4 key购买 nike

我有课

// final class from some library like okhttp
class NetworkCaller {
fun call() {
// performs some real operation
}
fun cancel() {
// .... cancels the request
}
}

class Request {
suspend fun asyncRequest(): String = suspendCancellableCoroutine { continuation ->
val call = NetworkCaller()
continuation.invokeOnCancellation {
call.cancel() // i need to write a test to mock if call.cancel is getting called or not
}
// rest of the code...
}
}

当我在做的时候

@Test
fun testRequestCancellation() {
val request = Request()
val job = GlobalScope.launch {
val response = request.asyncRequest()
println(response)
}
runBlocking {
job.cancel()
job.join()
}
}

作业正在被取消并且 continuation.invokeOnCancellation() 正在被调用,我检查了 println 语句。但我想模拟是否调用了 call.cancel 方法,使用 mockk 库。

我被困在这个问题上,需要帮助。

最佳答案

在您的类(class)中,公开 NetworkCaller 以便在测试期间将其切换为模拟:

class Request(val call: NetworkCaller = NetworkCaller()) {
suspend fun asyncRequest(): String = suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
call.cancel() // i need to write a test to mock if call.cancel is getting called or not
}
// rest of the code...
}
}

然后你就可以在你的测试中使用mockk了:

@Test
fun testRequestCancellation() {
val mockkCall = mockk<NetworkCaller> {
coEvery { cancel() } just Runs
}

val request = Request(mockkCall)
val job = GlobalScope.launch {
val response = request.asyncRequest()
println(response)
}
runBlocking {
job.cancel()
job.join()
}
coVerify { mockkCall.cancel() }
confirmVerified(mockkCall)
}

关于unit-testing - 暂停可取消协程取消的 Kotlin Mockk 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60957588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com