【发布时间】:2021-04-23 04:57:32
【问题描述】:
我尝试编写一个使用 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())
}
runTest 在 androidTest 和 iosTest 模块中的实际实现。
actual fun<T> runTest(block: suspend () -> T) { runBlocking { block() } }
我想当我使用 coroutineScope 时,它会等到所有子协程完成。我做错了什么,如何解决这个异常?
【问题讨论】:
-
你找到解决办法了吗?
-
协程范围,据我所知,将取消其他协程。如果您想将父作业与其他作业解耦,可以使用 CoroutineScope.launch,或者使用主管范围调用调用
标签: kotlin kotlin-coroutines ktor