Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Testing

Testing Ktor with Fakes, Mocks and Real Databases

Isolate the data layer when testing Ktor services. Compare fakes, mocks and real databases (H2, Testcontainers), design for testability with interfaces, and test error paths with runnable Kotlin.

Route tests from the previous lesson run your whole application. But an application talks to things you do not want in a unit test: a database, a payment gateway, an email service, the clock. This lesson is about test doubles (stand-ins for those collaborators), the difference between a fake, a stub and a mock, and when a real database in a test is better than any double.

The Ktor and library code is shown read-only; the runnable examples implement the same patterns in plain Kotlin.

Design for testability first

Testing gets easy when routes do not create their own dependencies. Define an interface, pass an implementation in, and the test can pass a different one.

Kotlin
interface TaskRepository {
    suspend fun all(): List<Task>
    suspend fun find(id: Int): Task?
    suspend fun add(title: String): Task
}

class ExposedTaskRepository : TaskRepository { /* real SQL */ }

fun Application.module(repository: TaskRepository = ExposedTaskRepository()) {
    install(ContentNegotiation) { json() }
    routing {
        get("/tasks/{id}") {
            val task = repository.find(call.parameters["id"]!!.toInt())
            if (task == null) call.respond(HttpStatusCode.NotFound) else call.respond(task)
        }
    }
}

The production main calls module() with the default; a test calls module(FakeTaskRepository()). No framework is required, which is why this style is common in Ktor projects. Larger apps use a dependency injection library (Koin, Kodein) and override the bindings in tests, but plain constructor and parameter passing goes a long way.

Fake, stub, mock: the vocabulary

  • A fake is a working lightweight implementation, such as a repository backed by a MutableMap. It has real behavior: add then find returns what you added.
  • A stub returns canned answers: "whenever find(1) is called, return this task".
  • A mock records the calls it receives so the test can verify them: "send was called once with this email".

For data access, fakes are usually best: tests read like the real behavior and do not break when you refactor how the repository is called. Use mocks for outgoing side effects (emails, notifications) where "was it called" is the point.

Kotlin Stand-in: a fake repository, and a recording mock

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 fake gave the service a working repository, and the recording mailer let the test verify that the failure path did not send an email. With the MockK library the same mailer check is verify(exactly = 1) { mailer.send("[email protected]", any()) }, and a stub is every { repo.find(1) } returns Task(1, "x"). MockK understands suspend functions with coEvery and coVerify.

Test the failure paths on purpose

Dependencies fail in real life, and a double can make them fail on demand: a repository that throws, a gateway that times out. Then assert that your route turns the failure into a clean response (a 503 or a 500 with a safe message) rather than a stack trace.

Kotlin
@Test
fun databaseFailureIs500() = testApplication {
    val broken = object : TaskRepository {
        override suspend fun find(id: Int): Task? = error("db down")
        override suspend fun all() = error("db down")
        override suspend fun add(title: String) = error("db down")
    }
    application { module(broken) }

    val response = client.get("/tasks/1")
    assertEquals(HttpStatusCode.InternalServerError, response.status)
    assertFalse(response.bodyAsText().contains("db down"))   // no internals leaked
}

That last assertion matters: the StatusPages plugin should log the details and return a generic body.

When to use a real database

A fake repository cannot catch a wrong SQL statement, a missing migration, a unique-constraint violation or a transaction bug. For those you want the real thing, at least in a smaller set of repository integration tests:

  • H2 in-memory: fast, no setup, good for most Exposed code. It is not identical to PostgreSQL, so avoid database-specific features in the tests or use H2's PostgreSQL mode.
  • Testcontainers: starts a real PostgreSQL or MySQL in Docker for the test run. Slower (seconds), but the SQL dialect and behavior match production.
Kotlin
class ExposedTaskRepositoryTest {
    companion object {
        private val postgres = PostgreSQLContainer("postgres:16-alpine").apply { start() }
    }

    @BeforeTest
    fun setUp() {
        val ds = HikariDataSource(HikariConfig().apply {
            jdbcUrl = postgres.jdbcUrl; username = postgres.username; password = postgres.password
        })
        Flyway.configure().dataSource(ds).load().migrate()      // the production schema
        Database.connect(ds)
        transaction { Tasks.deleteAll() }                       // clean state per test
    }

    @Test
    fun addThenFind() = runBlocking {
        val repo = ExposedTaskRepository()
        val saved = repo.add("Write tests")
        assertEquals("Write tests", repo.find(saved.id)?.title)
    }
}

Use the same migrations as production, and give every test a clean state: either delete rows in @BeforeTest, or wrap each test in a transaction that you roll back.

A deliberately small test pyramid

Layer Double? Speed Count
Pure functions (validation, price rules) none microseconds many
Routes with a fake repository fake milliseconds many
Repository with a real database none tens of ms some
Full flow with Testcontainers none seconds a few

Most behavior should be covered by the cheap layers; the expensive ones check the seams.

Controlling time and randomness

Code that reads Instant.now() or Random is hard to test. Inject a Clock (Java's java.time.Clock) and pass Clock.fixed(...) in tests. A runnable example makes the idea concrete.

Kotlin Stand-in: inject a fixed clock to test expiry

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.

No Thread.sleep, no flaky timing: the test moves the clock by hand.

Common mistakes

  • Mocking everything. Tests that assert on every internal call break at each refactor and prove little. Prefer fakes for your own code and mocks for outgoing effects.
  • Sharing a database between tests without cleaning it.
  • Different schema in tests than in production because tests use SchemaUtils.create and production uses Flyway.
  • Real time and random values inside code under test.
  • Only testing the happy path.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between a fake and a mock?

    Fakes behave like the real thing in a simpler way; mocks focus on verifying interactions.
  2. 2. Why pass a repository into module(...) as a parameter?

    Injecting the dependency lets tests control it.
  3. 3. Which problem can a fake repository NOT catch?

    Only a real database exercises SQL and schema.
  4. 4. How do you test code that depends on the current time without sleeping?

    An injected clock lets the test control time instantly.

Summary

  • Pass dependencies into your module so tests can replace them.
  • Prefer fakes for your own data layer, mocks for outgoing side effects, and stubs for canned answers.
  • Test failure paths by making doubles fail, and check that no internals leak.
  • Use H2 or Testcontainers with the production migrations for repository integration tests, with clean state per test.
  • Inject clocks and randomness.

Next: Testing WebSockets, SSE and Concurrent Code