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

标签 unit-testing kotlin junit4 junit5 mockk

我有课

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

相关文章:

使用 PowerMock 进行 Android 仪器测试

java - 注释方法 arg @Nonnull 时 JUnit 测试失败

java - 从Ant到Gradle:JUnit(4.11)测试转换

java - 更改参数化测试的名称

c# - 系统.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member

javascript - 关于如何使用 BusterJs 资源配置选项的好例子?

javascript - 预期等于结果时出现不可变的 Chai 断言错误

json - 使用 kotlinx.serialization 库反序列化具有不同值类型的 JSON 数组

android - Dagger 柄 : Repository cannot be provided without an @Provides-annotated method

android - Android在TextView上每个字母周围的边框