我试着写一个使用ktor的kotlin多平台库(android和ios)。因此,我经历了一些问题与kotlin协程:
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模块)。我的库中的所有方法都是以类似的方式编写的。如果是客户端,则会发生异常。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时,它会等到所有子coroutines都完成。我做错了什么?如何修复此异常?
必须更新库,此故障在此处的修复报告中:https://newreleases.io/project/github/ktorio/ktor/release/1.6.1
问题是您不能使用同一个HttpClient实例。我的ej:
HttpClient(CIO) {
install(JsonFeature) {
serializer = GsonSerializer()
}
}.use { client ->
return@use client.request("URL") {
method = HttpMethod.Get
}
}
您不能将CIO的HttpClient缓存在客户机变量中并重用,最好在实现中更改以下代码。
val client:HttpClient get() = HttpClient(MockEngine) {
engine {
addHandler { request ->
// Create response object
}
}
}