Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Testing

Testing Ktor Applications with testApplication

Test Ktor routes without opening a network port using testApplication and the test client. Cover status codes, JSON bodies, headers, cookies and error cases, with runnable Kotlin test-host models.

A web service you cannot test quickly is a service you are afraid to change. Ktor makes fast tests easy: its testApplication function starts your application inside the test process, with no real network port, and hands you an HTTP client that talks straight to it. A test then looks like a request in, assertions on the response out. Hundreds of such tests run in seconds.

The Ktor test code below is real and read-only here (it needs the Ktor test engine). To make the mechanics concrete, the runnable examples build a miniature "application as a function" and a small test client, which is conceptually what testApplication does for you.

Dependencies and the first test

Kotlin
dependencies {
    testImplementation("io.ktor:ktor-server-test-host:$ktorVersion")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5:$kotlinVersion")
}
Kotlin
class ApplicationTest {
    @Test
    fun rootReturnsGreeting() = testApplication {
        application { module() }

        val response = client.get("/")

        assertEquals(HttpStatusCode.OK, response.status)
        assertEquals("Hello, Ktor!", response.bodyAsText())
    }
}

What happens: application { module() } installs your real Application.module() function, the same one main runs, client is an HTTP client wired to that in-memory application, and get("/") runs the full pipeline: routing, plugins, content negotiation, status pages. testApplication is a suspend-based builder, so the test function returns its result (= testApplication { ... }).

If you use routing directly instead of a module, you can also declare routes inside the test:

Kotlin
@Test
fun customRouteInTest() = testApplication {
    routing { get("/ping") { call.respondText("pong") } }
    assertEquals("pong", client.get("/ping").bodyAsText())
}

Testing JSON endpoints

For JSON you want the client to serialize and deserialize like a real consumer. Create a client with the ContentNegotiation plugin:

Kotlin
@Test
fun createAndFetchTask() = testApplication {
    application { module() }
    val client = createClient {
        install(ContentNegotiation) { json() }
    }

    val created = client.post("/tasks") {
        contentType(ContentType.Application.Json)
        setBody(NewTask(title = "Write tests"))
    }
    assertEquals(HttpStatusCode.Created, created.status)
    val task = created.body<Task>()

    val fetched = client.get("/tasks/${task.id}").body<Task>()
    assertEquals("Write tests", fetched.title)
}

setBody serializes your data class; body<Task>() deserializes the response. If a route's JSON field is renamed, the compile error in the test points straight at the contract that changed.

What to assert

Good route tests check four things:

  1. Status code: 200, 201, 204, 400, 401, 404, 409. Test the failures, not only the happy path.
  2. Body: parsed into a type, or at least the important fields.
  3. Headers: Content-Type, Location after a create, Set-Cookie, caching headers.
  4. Side effects: what a following GET returns, or what a fake repository recorded.
Kotlin
@Test
fun unknownTaskIs404() = testApplication {
    application { module() }
    val response = client.get("/tasks/9999")
    assertEquals(HttpStatusCode.NotFound, response.status)
}

@Test
fun invalidBodyIs400() = testApplication {
    application { module() }
    val response = client.post("/tasks") {
        contentType(ContentType.Application.Json)
        setBody("""{"title": ""}""")
    }
    assertEquals(HttpStatusCode.BadRequest, response.status)
}

A model of a test host

Under the hood testApplication builds an application object and feeds it request objects. This runnable model uses a function (Request) -> Response as the application and a tiny client DSL, so you can see how a "no network" test works and write assertions in plain Kotlin.

Kotlin Stand-in: an app as a function and a test client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the pattern: a fresh application for every test. If tests share state (a static list, one database), their results depend on the order they run in, and that is the most frustrating kind of flaky test. In Ktor you get isolation for free because each testApplication { } starts a new application.

Cookies, redirects and headers

The test client has options that mirror real clients:

Kotlin
val client = createClient {
    install(HttpCookies)                  // keep session cookies between calls
    followRedirects = false               // assert on the 302 itself
}

val login = client.post("/login") { setBody("user=ann&password=secret") }
assertEquals(HttpStatusCode.Found, login.status)
assertEquals("/dashboard", login.headers[HttpHeaders.Location])

Turn off followRedirects when you want to assert the redirect; leave it on when you only care where the user ends up.

The model below has a login that sets a cookie, a protected page, and a client that stores cookies and can follow or ignore redirects, the same options you just saw.

Kotlin Stand-in: cookies and redirects in a test client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Configuration in tests

Tests should not read your production configuration. Override it:

Kotlin
testApplication {
    environment {
        config = MapApplicationConfig(
            "db.url" to "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
            "jwt.secret" to "test-secret",
        )
    }
    application { module() }
    // ...
}

Configuration and environments explains how the same keys are read in production. Writing your module so it takes its dependencies from configuration (or from parameters) is what makes this swap possible.

Structure a test suite

  • Put route tests (full pipeline, slower) next to unit tests of pure functions (validation, pricing rules), which need no Ktor at all.
  • Name tests by behavior: createTask_withBlankTitle_returns400.
  • One reason to fail per test; share setup in helper functions, not shared mutable state.
  • Run the suite in CI on every push. See testing with fakes and databases for isolating the data layer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does testApplication avoid?

    The application runs in memory with a client wired directly to it, which makes tests fast.
  2. 2. Why use a fresh application per test?

    Shared mutable state causes order-dependent flaky tests.
  3. 3. How do you make the test client send and read JSON objects?

    The plugin serializes setBody and deserializes body<T>().
  4. 4. When would you set followRedirects = false in a test client?

    With redirects off you can check the 302 status and where it points.

Summary

  • testApplication runs your real module in-process and gives you a client; no port, fast tests.
  • Test statuses (including 400, 401, 404), bodies, headers and side effects.
  • Use createClient { install(ContentNegotiation) { json() } } for typed JSON.
  • Override configuration in the test and create a fresh application per test.
  • Mix route tests with plain unit tests for business rules.

Next: Testing with Fakes and Databases