https://kotlinlang.org logo
#ktor
Title
# ktor
s

spawlak

09/25/2019, 2:07 PM
Hi folks. I'm playing around with ktor. I'm trying to write some integration tests for my REST resource that accepts JSON content. Right now I do it like in the snippet and everything is working. As you can see I have to "manually" serialize data object to JSON (
mapper.writeValue...
) and set it as a body for the request. Is there any nicer way to do this in integration tests and just provide and object that would be then later on automatically serialized by test framework??
1
c

cy

09/25/2019, 3:45 PM
Unfortunately, handleRequest is unable to do that. However, you can create a test ktor client that is configurable just as a regular ktor client and most features are available
Example:
Copy code
HttpClient(TestHttpClientEngine.config { app = this@withTestApplication }) {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
}.use { client ->
    val result = <http://client.post|client.post><String>() {
        url("<http://localhost/>")
        contentType(ContentType.Application.Json)
        body = MyEntity(1, "test", emptyList())
    }

    assertTrue { result.startsWith("MyEntity(") }
}
Notice
{ app = this@... }
Also
localhost
is just a placeholder, no actual networking is used
s

spawlak

09/25/2019, 4:21 PM
Cool! Thanks
m

mp

09/26/2019, 4:16 PM
Or just write an extension function
s

spawlak

09/30/2019, 4:53 PM
@cy It does not work for me 😞.
Untitled
I'm getting NPE.
Untitled
It looks like the status of response is null.
I check with debugger and it seems fine the request path is definitely fine.
2 Views