kotlin - 如何在 ktor Kotlin 中创建具有虚拟值的 HttpResponse 对象?

标签 kotlin httpresponse ktor

我正在使用 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/

相关文章:

kotlin - 具有实现该接口(interface)的类的泛型类型的接口(interface)?

android - Kotlin 中对象/私有(private)构造函数/伴生对象之间的区别?

interface - 初始化接口(interface)实例变量

docker - 使用 Postgresql 数据库在 docker 容器中运行简单的 Kotlin Ktor 应用程序

KMM iOS 中的 kotlin.native.concurrent.InvalidMutabilityException : mutation attempt of frozen kotlin. collections.HashMap@3ee0f08

kotlin - 数据类中的默认参数未使用 ktor 序列化程序转换为 json

android - 使用 Dispatchers.IO 进行 Kotlin 协程测试

iis - 删除服务器响应 header IIS 8.0/8.5

node.js - 通过 NodeJS 中的 Base64 编码处理图像/jpeg 响应并在 UI 上显示

asp.net - 使用 Http Response.Disable KernelCache