在 Ktor 中测试 Post 请求

Aha*_*ine 5 http kotlin ktor

Ktor(kotlin web 框架)有一个很棒的可测试模式,可以将 http 请求包装在单元测试中。他们给出了一个很好的例子,说明如何在此处测试 GET 端点,但是我在使用 http POST 时遇到了问题。

我试过了,但帖子参数似乎没有添加到请求中:

    @Test
fun testSomePostThing() = withTestApplication(Application::myModule) {
    with(handleRequest(HttpMethod.Post, "/api/v2/processing") {
        addHeader("content-type", "application/x-www-form-urlencoded")
        addHeader("Accept", "application/json")
        body = "param1=cool7&param2=awesome4"
    }) {
        assertEquals(HttpStatusCode.OK, response.status())
        val resp = mapper.readValue<TriggerResponse>(response.content ?: "")
        assertEquals(TriggerResponse("cool7", "awesome4", true), resp)
    }
}
Run Code Online (Sandbox Code Playgroud)

谁有想法?

Aha*_*ine 2

好吧,愚蠢的错误,我将其发布在这里,以防其他人浪费时间;)单元测试实际上捕获了一个真正的问题(我猜这就是它们的目的)在我的路由中我使用的是:

install(Routing) {
        post("/api/v2/processing") {
            val params = call.parameters
            ...
        }
}
Run Code Online (Sandbox Code Playgroud)

然而,这只适用于“获取”参数。帖子参数需要:

install(Routing) {
        post("/api/v2/processing") {
            val params = call.receive<ValuesMap>()
            ...
        }
}
Run Code Online (Sandbox Code Playgroud)