Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Testing

Testing WebSockets, SSE and Concurrent Code in Ktor

Test Ktor WebSocket and SSE routes with the test client, and write deterministic tests for coroutine code using runTest, virtual time and Turbine-style flow assertions in runnable Kotlin.

HTTP request and response tests are straightforward: one call, one answer. Real-time code is harder. A WebSocket conversation has several messages in both directions, an SSE stream never ends, and anything involving delay or timeouts tempts you to write tests that sleep. This lesson shows how to test those routes with the Ktor test client and, more importantly, how to test coroutine code deterministically with virtual time.

As elsewhere, the Ktor test code is real but read-only (it needs the Ktor engine), and the runnable parts rebuild the same techniques with kotlinx-coroutines.

WebSocket routes with the test client

The test client needs the client-side WebSockets plugin. client.webSocket(path) { } opens a session; inside the block you use send, incoming and close like the server does, but from the client's point of view.

Kotlin
@Test
fun echoRoute() = testApplication {
    application { module() }
    val client = createClient { install(WebSockets) }

    client.webSocket("/echo") {
        assertEquals("Connected. Say something!", (incoming.receive() as Frame.Text).readText())

        send("hello")
        assertEquals("You said: hello", (incoming.receive() as Frame.Text).readText())

        send("kotlin")
        assertEquals("You said: kotlin", (incoming.receive() as Frame.Text).readText())
    }
}

incoming.receive() suspends until a frame arrives, so the test needs no sleeps. If the route never answers, the test would hang, so give tests a timeout (JUnit's @Timeout(10) or withTimeout(5.seconds) around the block).

To test broadcasting you need two clients in the same test, each in its own coroutine:

Kotlin
@Test
fun messageReachesOtherUser() = testApplication {
    application { module() }
    val client = createClient { install(WebSockets) }

    coroutineScope {
        val bobSaw = async {
            client.webSocket("/chat?user=bob") {
                (incoming.receive() as Frame.Text).readText()
            }
        }
        yield()
        client.webSocket("/chat?user=ann") { send("hi everyone") }
        assertEquals("ann: hi everyone", bobSaw.await())
    }
}

SSE routes

For Server-Sent Events, use the client-side SSE plugin and read events as a flow; since the stream may be infinite, take only what you need:

Kotlin
@Test
fun clockSendsTicks() = testApplication {
    application { module() }
    val client = createClient { install(SSE) }

    client.sse("/clock") {
        val firstThree = incoming.take(3).map { it.data }.toList()
        assertEquals(listOf("tick 0", "tick 1", "tick 2"), firstThree)
    }
}

take(3) ends the collection and the client closes the connection, so the test finishes while the server route is cancelled.

Why sleeping tests are a trap

A test that says delay(2000) and then asserts is slow and still unreliable on a busy build machine. The cure is virtual time. kotlinx-coroutines-test provides runTest, which runs your coroutines on a test scheduler that skips delays instantly, advancing a fake clock. A function that waits an hour finishes in microseconds, and the order of events stays deterministic.

Kotlin
dependencies {
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion")
}

@Test
fun retryWaitsBetweenAttempts() = runTest {
    var attempts = 0
    val result = retry(times = 3, delayMs = 1_000) { if (++attempts < 3) error("fail") else "ok" }
    assertEquals("ok", result)
    assertEquals(2_000, currentTime)       // virtual time advanced, real time did not
}

The runner here has kotlinx.coroutines but not the -test artifact, so the next example builds a tiny virtual-time scheduler by hand. It is a teaching model, but it shows exactly what runTest does.

Kotlin Stand-in: a virtual clock that skips delays

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.

Five virtual seconds elapsed, almost no real time. In a real runTest the same trick applies to delay, withTimeout and Flow operators like debounce.

Testing flows

Collect a flow into a list to assert on it. For an infinite flow, take a fixed number:

Kotlin Collect, take and assert on a Flow

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.

The last check really waits 250 ms. In a runTest it would be instant; with plain runBlocking keep timeouts short.

Tests that spawn background work

If a route starts background coroutines in an application scope, a test must either wait for them (with a latch such as CompletableDeferred) or cancel them at the end, otherwise they leak into the next test. Give long-running components an injected CoroutineScope (or dispatcher) so tests control it:

Kotlin
class Poller(private val scope: CoroutineScope, private val fetch: suspend () -> Unit) {
    fun start() = scope.launch { while (isActive) { fetch(); delay(30_000) } }
}
// in a test: Poller(TestScope(), fake).start(); advanceTimeBy(65_000); assert...

A checklist for real-time tests

  • Receive with incoming.receive(), never with delay.
  • Put a timeout on every test that waits for the network.
  • Use two clients for broadcast tests and close them in finally.
  • Use runTest and virtual time for retries, timeouts, debouncing and periodic jobs.
  • Make time, dispatchers and scopes injectable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How should a WebSocket test wait for the server's reply?

    Receiving suspends exactly as long as needed and avoids sleeping.
  2. 2. What does runTest do with delay(60_000)?

    The test scheduler advances virtual time instead of waiting.
  3. 3. How do you test an infinite SSE stream?

    take(n) ends the collection, which closes the connection.
  4. 4. Why inject a CoroutineScope into long-running components?

    A test-controlled scope prevents leaks and makes time deterministic.

Summary

  • Open WebSocket and SSE sessions with the test client and read frames or events with suspending receives.
  • Use two clients to test broadcasting, and always put timeouts on network-waiting tests.
  • runTest provides virtual time so delays and timeouts cost nothing and stay deterministic.
  • Assert on flows by collecting or taking values; inject scopes and clocks so background work is controllable.

Next: Coroutines in Ktor