kotlin - 有什么方法可以从 Ktor 向自身发出假调用,以使请求通过所有管道?
问题描述
我有一个成功响应 http 请求的 ktor Web 服务器。现在需要从kafka的topic中读取数据并进行处理。有什么方法可以将我读过的数据发送到 ktor,就像这些数据来自外部一样,让它通过所有管道,比如 ContentNegotiation 和其他功能?
应用程序类有方法execute(),它接受ApplicationCall,但我发现零个例子——我怎样才能正确地填充我的这个类的实现。特别是路线 - 我需要真正的路线吗?如果这条路线是私人的并且从外面无法使用,那就太好了。
解决方案
您可以使用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()}" }
}
}
}
推荐阅读
- java - 空指针指向方法 getItemCount。我应该初始化那个方法吗?
- fastlane - Fastlane:使用设备更新更新匹配配置文件
- nestjs - 无法在会话变量中设置未定义的属性“userId”
- python - 表单不会验证,说所有字段都是空的 Django
- python - Python OpenCV - 图像四肢计算
- python - python中指数投资组合的跨度
- python - 有什么方法可以在 Python tkinter gui 中按比例放大点(x,y)?
- c# - C# 求函数的逆
- rescript - 使用 CLI 编译 Rescript -- 没有 bsconfig.json
- awk - Replace each nth occurrence of 'foo' and 'bar' by numerically respective nth line of a supplied file once time