Ktor(kotlin 网络框架)有一个很棒的可测试模式,其中可以将 http 请求包装在单元测试中。他们给出了一个很好的例子来说明如何测试 GET 端点 here , 但是我在使用 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¶m2=awesome4"
}) {
assertEquals(HttpStatusCode.OK, response.status())
val resp = mapper.readValue<TriggerResponse>(response.content ?: "")
assertEquals(TriggerResponse("cool7", "awesome4", true), resp)
}
}
有人有什么想法吗?
最佳答案
对于那些使用备用 .apply
来验证结果的人,您可以在测试调用之前添加正文
withTestApplication({ module(testing = true) }) {
handleRequest(HttpMethod.Post, "/"){
setBody(...)
}.apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals("HELLO WORLD!", response.content)
}
}
关于http - 在 Ktor 中测试 Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040613/