我正在使用 ktor 在 Kotlin 中开发微服务。为了测试方法,我需要创建一个虚拟 HttpResponse(具体来说是 io.ktor.client.statement.HttpResponse)对象,其 status = 200 且 body = 一些 json 数据。
知道如何创建它吗?
最佳答案
对于 Ktor 2,最好使用 externalServices
block ,而不是尝试模拟 HttpResponse
。这样你就不需要尝试和模拟 Ktor 的内部结构,而且一点也不复杂。
externalServices {
hosts("https://your-fake-host") {
routing {
get("/api/v1/something/{id}/") {
call.respondText(
"{}",
contentType = ContentType.Application.Json,
status = HttpStatusCode.OK
)
}
}
}
}
这需要用testApplication
包装
关于kotlin - 如何在 ktor Kotlin 中创建具有虚拟值的 HttpResponse 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71030142/