Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Post requests in Ktor

Tags:

http

kotlin

ktor

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&param2=awesome4"
    }) {
        assertEquals(HttpStatusCode.OK, response.status())
        val resp = mapper.readValue<TriggerResponse>(response.content ?: "")
        assertEquals(TriggerResponse("cool7", "awesome4", true), resp)
    }
}

Anyone have any ideas?

like image 503
Aharon Levine Avatar asked Dec 31 '17 06:12

Aharon Levine


2 Answers

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)
            }
        }
like image 63
jpthesolver2 Avatar answered Nov 15 '22 01:11

jpthesolver2


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>()
            ...
        }
}
like image 45
Aharon Levine Avatar answered Nov 15 '22 01:11

Aharon Levine