我尝试编写一个使用 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/