首页 > 解决方案 > 有什么方法可以从 Ktor 向自身发出假调用,以使请求通过所有管道?

问题描述

我有一个成功响应 http 请求的 ktor Web 服务器。现在需要从kafka的topic中读取数据并进行处理。有什么方法可以将我读过的数据发送到 ktor,就像这些数据来自外部一样,让它通过所有管道,比如 ContentNegotiation 和其他功能?

应用程序类有方法execute(),它接受ApplicationCall,但我发现零个例子——我怎样才能正确地填充我的这个类的实现。特别是路线 - 我需要真正的路线吗?如果这条路线是私人的并且从外面无法使用,那就太好了。

标签: kotlinapache-kafkahttpserverktor

解决方案


您可以使用withTestApplication函数来测试应用程序的模块,而无需进行实际的网络连接。这是一个例子:

import io.ktor.application.*
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.testing.*
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals

class SimpleTest {
    @Test
    fun test() = withTestApplication {
        application.module()
        // more modules to test here

        handleRequest(HttpMethod.Post, "/post") {
            setBody("kafka data")
        }.response.let { response ->
            assertEquals("I get kafka data", response.content)
        }
    }
}

fun Application.module() {
    routing {
        post("/post") {
            call.respondText { "I get ${call.receiveText()}" }
        }
    }
}

推荐阅读