Kotlin Mockk测试,用于暂停可取消的协程取消

问题描述 投票:0回答:1

我有课程

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方法是否被调用。

我对此感到困惑,需要帮助。

unit-testing kotlin junit4 junit5 mockk
1个回答
0
投票
package org.example

import kotlinx.coroutines.suspendCancellableCoroutine

interface CancellableAction {
    fun call()
    fun cancel()
}

class NetworkCaller : CancellableAction {
    override fun call() {
        // performs some real operation
    }

    override fun cancel() {
        // .... cancels the request
    }
}

class Request(val call: CancellableAction) {
    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...
    }
}

测试文件

package org.example

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Test

internal class NetworkCallerTest {
    @Test
    fun testRequestCancellation() {
        var callFunctionInvoked = false
        var cancelFunctionInvoked = false
        val request = Request(object : CancellableAction {
            override fun call() {
                callFunctionInvoked = true
            }

            override fun cancel() {
                cancelFunctionInvoked = true
            }
        })
        val job = GlobalScope.launch {
            val response = request.asyncRequest()
            println(response)
        }
        runBlocking {
            job.cancel()
            job.join()
        }

        assert(cancelFunctionInvoked)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.