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

How to create an HttpResponse object with dummy values in ktor Kotlin?

我正在使用 ktor 在 Kotlin 中开发微服务。为了测试一个方法,我需要创建一个虚拟 HttpResponse(io.ktor.client.statement.HttpResponse 对象)状态 = 200 和主体 = 一些 json 数据。
知道如何创建它吗?

您可以使用 mockk 或类似类型的库来模拟 HttpResponse。不幸的是,这很复杂,因为 HttpRequestHttpResponseHttpClient 对象与 HttpClientCall 紧密耦合。以下是如何执行此操作的示例:

val call = mockk<HttpClientCall> {
    every { client } returns mockk {}
    coEvery { receive(io.ktor.util.reflect.typeInfo<String>()) } returns "body"
    every { coroutineContext } returns EmptyCoroutineContext
    every { attributes } returns Attributes()
    every { request } returns object : HttpRequest {
        override val call: HttpClientCall = this@mockk
        override val attributes: Attributes = Attributes()
        override val content: OutgoingContent = object : OutgoingContent.NoContent() {}
        override val headers: Headers = Headers.Empty
        override val method: HttpMethod = HttpMethod.Get
        override val url: Url = Url("/")
    }

    every { response } returns object : HttpResponse() {
        override val call: HttpClientCall = this@mockk
        override val content: ByteReadChannel = ByteReadChannel("body")
        override val coroutineContext: CoroutineContext = EmptyCoroutineContext
        override val headers: Headers = Headers.Empty
        override val requestTime: GMTDate = GMTDate.START
        override val responseTime: GMTDate = GMTDate.START
        override val status: HttpStatusCode = HttpStatusCode.OK
        override val version: HttpProtocolVersion = HttpProtocolVersion.HTTP_1_1
    }
}

val response = call.response