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

Anders Sveen

12/14/2023, 8:30 AM
Hi. We're using KTor Server testing extensively and would like to set up the client to have ContentNegotiation by default. We can of course do this by doing createClient { ... } and using it locally in the tests, but I was hoping for a way to override for all tests by default. ClientProvider seems a decent clue, but couldn't find a way to register and alternative etc... Any pointers? 🙂
a

Aleksei Tirman [JB]

12/14/2023, 3:03 PM
The simplest way would be to create an extension function which would create a client with the predefined set of installed plugins.
Also, you can create a class-wide instance of a client with the
ContentNegotiation
plugin installed. Here is an example:
Copy code
class KtorTest {
    companion object {
        private lateinit var server: TestApplicationEngine
        private val client: HttpClient get() = HttpClient(TestHttpClientEngine.create { app = server }) {
            install(ContentNegotiation) {
                json()
            }
        }

        @BeforeClass
        @JvmStatic
        fun setup() {
            server = TestApplicationEngine(createTestEnvironment {
                module {
                    routing {
                        get {
                            call.respondText(contentType = ContentType.Application.Json) { """{"x": 42}""" }
                        }
                    }
                }
            })

            server.start(wait = false)
        }

        @AfterClass
        @JvmStatic
        fun tearDown() {
            server.stop()
        }
    }

    @Serializable
    data class Response(val x: Int)

    @Test
    fun test() = testSuspend {
        assertEquals(42, client.get("/").body<Response>().x)
    }
}
a

Anders Sveen

12/15/2023, 8:10 AM
Mmm, yeah. I was hoping to update the "default" client exposed by ApplicationTestBuilder but I guess there's really no available hook for that. 😕 Would be nice though. 🙂