Kest

Search

Search the documentation

Fundamentals

Testing

Test with the real application, replace only what you must.

Kest is designed so that tests use the real application, not a pile of mocks. You start your module (or a slice of it), replace the few things that talk to the outside world (an email service, a payment API), and call it over real HTTP.

A first test

class OrdersTest {
    @Test fun `placing an order returns 201 and sends a mail`() {
        val mailer = FakeMailer()
        val module = Testing.createModule<AppModule> {
            overrideProvider(Mailer::class, mailer)                                       // replace one provider with a fake
            overrideGuard(JwtAuthGuard::class) { ctx -> ctx.principal = SimplePrincipal("test-user", setOf("admin")); true }   // skip real login
        }
        val server = module.startHttp(NettyHttpAdapter(0)) { usePipes(ValidationPipe::class) }       // port 0: any free port
        try {
            server.post("/orders", """{"item":"boots","quantity":1}""").expectStatus(201).expectBodyContains("boots")
            assertEquals(1, mailer.sent.size)
            server.post("/orders", """{"quantity":0}""").expectStatus(400)               // test the refusals too
        } finally { module.close() }                                                      // stops the server and the container
    }
}

NestJS's Test.createTestingModule(...).overrideGuard(X).useValue(y).compile() becomes the block above.

What you can replace

HelperReplaces
overrideGuard(Type::class)the guard with one that lets every request through
overrideGuard(Type::class) { ctx -> ... }with a function that decides (and may set ctx.principal)
overrideGuard(Type::class, fake), overrideInterceptor, overridePipe, overrideFilter, overrideMiddlewarewith your own instance
overrideProvider(Type::class, instance), overrideProvider(Type::class) { ... }any provider, with any object (a hand-written fake or a mock)
override<T>(instance), provide<T> { r -> ... }, provideAsyncthe core operations the above are built on

Overrides take effect wherever the type is used (@UseGuards, a composed decorator, a global guard), because those are all resolved from the container.

The test client

TestServer has get, post, put, patch, delete and send. A TestResponse has status, text, body, header(name) and expectStatus, expectHeader, expectBodyContains. It does not follow redirects, so you can assert on them.

val r = server.get("/orders/1", mapOf("authorization" to "Bearer t"))
assertEquals(200, r.status)
assertEquals("application/json", r.header("content-type")?.substringBefore(';'))

Three levels of test

LevelHowSpeedCatches
Unitnew the class with fakes; no frameworkinstantlogic bugs in one class
SlicecreateModule<OrdersModule> with fakes for the edgesfastwiring and one feature end to end
FullcreateModule<AppModule> with real databasesslowerreal integration

Most tests belong in the first two. A unit test needs nothing from Kest: your classes are plain Kotlin with constructor parameters, so pass a fake in.

Real servers

The repository's own tests run against real PostgreSQL, MySQL, MongoDB, Redis, Memcached, NATS, RabbitMQ, MQTT, Kafka, an SMTP server, and Loki, Prometheus, Tempo and Grafana, started by tools/test-infra.sh up all (and removed by down). A test whose server is not reachable skips itself, so ./gradlew build still works on a machine without Docker, but then it proves less. Prefer a real database over a mocked one for repository tests: a mock cannot tell you your SQL is wrong.

Tests that need time or randomness

Pass a clock or a seed into the class (a constructor parameter or an option such as the workflow clock) instead of calling Instant.now() inside, so a test can control it. Several packages take such options (sleeper, clock) for this reason.

Concurrency in tests

Handlers run in parallel, so test shared components from many threads: submit work to a fixed pool and assert on exact totals. The framework's own tests do this for the metrics registry, the cache stores, sagas and a decorated bean.

Good practice

  • Always close the module (finally { module.close() } or a JUnit @AfterEach): leaked database pools make later tests fail or skip.
  • Test the refusals (400, 401, 403, 404, 409), not only the happy path.
  • Use a fresh module per test, or reset shared state, so tests do not depend on order.
  • Keep fakes small and honest: a FakeMailer that records messages is better than a mock that replays a script.

Read more