Hi all, my current Ktor server tests look like thi...
# ktor
j
Hi all, my current Ktor server tests look like this
Copy code
@Test
fun testBasicCreate() = testApplication {
    application {
        configureSerialization()
    }
    routing {
        userRouting()
    }
    val client = createClient {
        install(ContentNegotiation) {
            json(
                Json {
                    ignoreUnknownKeys = true
                    isLenient = true
                    prettyPrint = true
                },
                contentType = ContentType.Application.Json
            )
        }
    }
    ...
    test code
    ...
}
where everything before the actual test code is duplicated at the start of each test. Is there a way to put this code in one place and remove the duplicates? Thanks
e
Copy code
fun TestApplicationBuilder.commonSetup() {
    ...
}

@Test
fun testBasicCreate() = testApplication {
    commonSetup()
    ...
}
or
Copy code
fun myTestApplication(block: TestApplicationBuilder.() -> Unit) = testApplication {
    ...
    block()
}
.
@Test
fun testBasicCreate() = myTestApplication {
    ...
}
j
Ok great, this was what I was looking for. Is there also a way to also initialize a client in such a setup function?
a
Also, you can define a wrapper function for the
testApplication
function:
Copy code
fun testApp(block: suspend (HttpClient) -> Unit) = testApplication {
    application {
        configureSerialization()
    }
    routing {
        userRouting()
    }

    val client = createClient {
        install(ContentNegotiation) {
            json(
                Json {
                    ignoreUnknownKeys = true
                    isLenient = true
                    prettyPrint = true
                },
                contentType = ContentType.Application.Json
            )
        }
    }

    block(client)
}
Here is a simple test:
Copy code
@Test
fun testBasicCreate() = testApp { client ->
    assertEquals("OK", client.get("/").bodyAsText())
}
👍 1
j
Perfect, thanks so much!