https://kotlinlang.org logo
Title
r

Renaud

04/22/2022, 1:58 PM
Trying to write tests on Ktor2 with kotlinx-serialization. I’m getting this error:
No request transformation found
. Does it sound familiar to someone? Looking a ktor source code, it comes from HttpRequest.kt
body as? OutgoingContent ?: error("No request transformation found: $body")
It seems related to the setBody function in my test
@Test
    fun testPostRandom() = testApplication {
        val response = <http://client.post|client.post>("/random") {
            contentType(ContentType.Application.Json)
            setBody(PostRandomRequest(listOf("Jet", "Brains")))

        }
        assertEquals("Hello World!", response.bodyAsText())
        assertEquals(HttpStatusCode.Created, response.status)
    }
a

Aleksei Tirman [JB]

04/22/2022, 2:15 PM
You need to install the
ContentNegotiation
plugin into the client to serialize the request body:
val client = createClient {
    install(ContentNegotiation) {
        json()
    }
}
val response = <http://client.post|client.post>("/random") {
    contentType(ContentType.Application.Json)
    setBody(PostRandomRequest(listOf("Jet", "Brains")))

}
assertEquals("Hello World!", response.bodyAsText())
assertEquals(HttpStatusCode.Created, response.status)
r

Renaud

04/22/2022, 2:26 PM
I’ve tried this approach unsuccessfully 😞
val client = createClient {
    this@testApplication.install(ContentNegotiation)
    ...
But since I’m using HOCON config file, according to the doc:
Add modules automatically
If you have the
application.conf
file in the
resources
folder,
testApplication
loads all modules and properties specified in the configuration file automatically.
p

phldavies

04/22/2022, 2:27 PM
you need to bring in the right
ContentNegotiation
for the client, not the server version
👍 1
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
or
createClient {    
    install(io.ktor.client.plugins.contentnegotiation.ContentNegotiation) 
}
the HOCON configuration file will configure the server/application for you, but not the client afaik (certainly not in the test application).
:yes: 1
r

Renaud

04/22/2022, 3:08 PM
It works, awesome. Thanks @phldavies 👏
🙌 1