Kotlin 多平台 : JobCancellationException: Parent job is Completed

标签 kotlin kotlin-coroutines ktor

我尝试编写一个使用 ktor 的 kotlin 多平台库(android 和 ios)。因此,我在使用 kotlins 协程时遇到了一些问题:

When writing tests I always get kotlinx.coroutines.JobCancellationException: Parent job is Completed; job=JobImpl{Completed}@... exception.

我使用 ktors 模拟引擎进行测试:

client = HttpClient(MockEngine) 
{
    engine 
    {
         addHandler 
         { request ->
             // Create response object
         }
     }
}

使用 ktor 的示例方法(commonMain 模块)。我的库中的所有方法都是以类似的方式编写的。如果调用 client.get 会发生异常。

suspend fun getData(): Either<Exception, String> = coroutineScope 
{
     // Exception occurs in this line:
     val response: HttpResponse = client.get { url("https://www.google.com") }

     return if (response.status == HttpStatusCode.OK) 
     {
         (response.readText() as T).right()
     } 
     else 
     {
        Exception("Error").left()
     }
}

上述方法的示例单元测试(commonTest 模块)。从未调用 assertTrue 语句,因为之前抛出了异常。

@Test
fun getDataTest() = runTest 
{
    val result = getData()
    assertTrue(result.isRight())
}

androidTest 和 iosTest 模块中 runTest 的实际实现。

actual fun<T> runTest(block: suspend () -> T) { runBlocking { block() } }

我想当我使用 coroutineScope 时,它会等到所有子协程都完成。我做错了什么,我该如何解决这个异常?

最佳答案

不能在client变量中缓存CIO的HttpClient并重用,最好在实现中改一下下面的代码。

val client:HttpClient get() = HttpClient(MockEngine) {
    engine {
         addHandler { request ->
             // Create response object
         }
     }
}

关于Kotlin 多平台 : JobCancellationException: Parent job is Completed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65782244/

相关文章:

kotlin - 在Kotlin中异步将项目添加到MutableList

kotlin - "Receiver class does not define or inherit an implementation"与 RestAssured 4.3.0

android - 何时使用 Kotlin 协程来优化代码性能

android - Kotlin 流 : unsubscribe from SharedFlow when Fragment becomes invisible

使用 TestCoroutineDispatcher(已弃用)替代方案对 Kotlin 协程进行 Android 测试

lambda - kotlin如何在多层应用函数中引用外部范围

gradle - IntelliJ IDEA with Kotlin 无法访问另一个模块所需的类

kotlin - Ktor路由: How to factorize the routing functionality in an application/api?

kotlin - 无法使用 Ktor 提供静态内容

java - 如何在 ktor 应用程序中注入(inject)依赖项