Ktor (kotlin web framework) has an awesome testable mode where http requests can be wrapped in unit tests. They give a nice example of how to test a GET endpoint here, however I'm having trouble with an http POST.
I tried this but the post params don't seem to be added to the request:
@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)
}
}
Anyone have any ideas?
For those using the alternate .apply
to verify results, you can prepend the body before the test call
withTestApplication({ module(testing = true) }) {
handleRequest(HttpMethod.Post, "/"){
setBody(...)
}.apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals("HELLO WORLD!", response.content)
}
}
Ok dumb mistake, I'll post it here in case this saves somebody else from wasting time ;) The unit test was actually catching a real problem (thats what they're for I guess) In my routing I was using:
install(Routing) {
post("/api/v2/processing") {
val params = call.parameters
...
}
}
However that only works for 'get' params. Post params need:
install(Routing) {
post("/api/v2/processing") {
val params = call.receive<ValuesMap>()
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With