Kandra

Testing

kandra-test offers two genuinely different testing styles, and they are not a fast/slow version of the same thing — they exercise different amounts of the real system, and mixing up which one covers what is exactly the mistake this page exists to prevent.

StyleEntry pointBackingSpeedWhat it actually exercises
Fake-session unit testKandraTestUtils.inMemory(...)FakeKandraSession — in-process, no networkInstantThe real repository/StatementBuilder/BatchEngine code paths, with structural assertions on the statements they build — no stored data, no rows back
Testcontainers integration testKandraTestcontainers.freshKeyspace(...)Real cassandra:4.1 containerSlow (container start + real CQL)The full, real KandraRepository/KandraSuspendRepository API against real DDL/DML

FakeKandraSession records statements; it does not store data

FakeKandraSession's own KDoc says it lets you "wire a full repository stack without Testcontainers." That is true today, with one qualifier that matters: the whole stack runs, but nothing is stored. Read what it does:

kandra-test/.../FakeKandraSession.kt
override fun execute(statement: Statement<*>): ResultSet {
    capturedStatementsList.add(statement)
    return FakeResultSet.empty()
}
 
override fun prepare(query: String): PreparedStatement = FakePreparedStatement(query)   // .bind(...) records values

prepare(cql).bind(...) returns a structural FakeBoundStatement that remembers the bound values positionally, so every real statement-building path in StatementBuilder — insertPrimary, insertLookup, deleteById, selectById, the versioned UPDATE ... IF version = ? builder, counterUpdate, findPage — completes. repo.save(entity), repo.update(old, new) and repo.delete(entity) therefore run through the real BatchEngine and leave their LOGGED batches in capturedBatches() for you to assert on.

This used to throw — it was fixed in 0.4.7

Before GH #28 / ISS-040, FakePreparedStatement.bind(...) unconditionally threw UnsupportedOperationException, so every repository call failed immediately under KandraTestUtils.inMemory(...). If you have older notes or blog posts saying "repository calls throw under the fake", they describe that earlier behavior.

What it is good for — asserting on how a repository call built its writes, without spinning up a container:

class SaveStructureTest {
    @AfterEach fun tearDown() = SchemaRegistry.clear()
 
    @Test
    fun `save builds one LOGGED batch with the expected INSERT`() {
        val runtime = KandraTestUtils.inMemory(User::class)
        val session = runtime.session as FakeKandraSession
        val repo = runtime.repository(User::class)
 
        repo.save(User(id = "u1", name = "Ada"))
 
        val batch = session.capturedBatches().single()
        val queries = batch.map { (it as BoundStatement).preparedStatement.query }
        assertEquals(listOf("INSERT INTO users (id, name) VALUES (?, ?)"), queries)
        runtime.close()
    }
}

Use runtime.session rather than constructing a separate FakeKandraSession() — inMemory(...) wires its own instance.

Why the fake stops at structure

This is the load-bearing distinction: FakeKandraSession's narrowness is a documented, accepted limitation, not a defect waiting on a fix.

ISS-020: FakeKandraSession never exercises real LWT/bind() semantics

BatchEngine.saveIfNotExists and the optimistic-lock update() path both check rs.one()?.getBoolean("[applied]") ?: false to decide whether an LWT succeeded. Under FakeKandraSession, execute() always returns FakeResultSet.empty(), so that check always evaluates false — and FakeBoundStatement performs no CQL type encoding or decoding. The practical effect: unit tests written against the fake have effectively zero coverage of the outcome of saveIfNotExists, optimistic-lock update(), and collection mutation — they can show the statements were built, never that the database accepted or rejected them.

Why it isn't "fixed": FakeKandraSession's own doc comment says it exists for asserting structural behavior — "batch composition, save/delete ordering... rather than data round-trips." Making it simulate real LWT semantics (a configurable wasApplied(), real row storage, real type-aware binding) means re-implementing a meaningful chunk of Cassandra's data-plane behavior inside a test double — precisely the job KandraTestcontainers (a real Cassandra container) already does correctly, by construction, because it is the real thing. The fix that was accepted here isn't a smarter fake — it's real-database integration tests via Testcontainers.

Takeaway, stated plainly: a green suite of fake-session unit tests is not evidence that saveIfNotExists, optimistic locking, or collection mutation work. Those paths are exercised for the first time by the Testcontainers suite. If your test suite is 100% fake-session tests and 0% Testcontainers, you have real, uncovered gaps at exactly the places Cassandra's behavior differs most from a naive mock.

There's no seam to work around this either — FakeResultSet.wasApplied() is hardcoded true, with no override point, and tableContents(tableName) always returns emptyList() regardless of what was "written." Don't reach for either to assert on saved data or simulate a conflict; there's nothing behind them to configure.

KandraTestcontainers: the real thing, run against a real database

KandraTestcontainers.freshKeyspace(...) builds the actual production io.kandra.runtime.KandraRuntime — the same class Ktor wires up — against a real Cassandra container, with a fresh, randomly-named keyspace per call so parallel test classes don't collide:

class UserRepositoryIntegrationTest {
    private val db = KandraTestcontainers.freshKeyspace(User::class)
    private val userRepo = db.repository<User>()   // reified — no ::class argument here
 
    @AfterEach fun tearDown() = db.close()          // drops db.keyspace; the shared container stays up
 
    @Test
    fun `save then findById round-trips through real CQL`() {
        val user = User(id = "u1", name = "Ada", email = "ada@example.com")
        userRepo.save(user)
        assertEquals(user, userRepo.findById(user.id))
    }
}

This is where saveIfNotExists, @Version conflicts, collection append/remove, and everything else that depends on real Cassandra semantics actually gets exercised.

Cassandra 4.1, not ScyllaDB — and a JVM-wide singleton container

KandraTestcontainers.container is cassandra:4.1, not a ScyllaDB image — tests run against Cassandra-protocol compatibility, not the literal production target. It's also a by lazy (thread-safe) singleton shared by every test class in the JVM run: the first access, from whichever test class hits it first, blocks synchronously while the container starts — expect the first integration test in a run to be noticeably slower than the rest. db.close() drops the per-call keyspace and closes that call's own session, wrapped in runCatching (a failed teardown won't fail your test or log anything) — it does not stop the shared container. SchemaRegistry is process-global and neither test style clears it automatically; call SchemaRegistry.clear() yourself in @AfterEach if a test depends on a clean registry.

Which one to reach for

  • Structural assertions (did save() build N statements, in what order, with which CQL) — FakeKandraSession. Fast, no Docker required, and it runs the real repository code.
  • Anything about the data or the outcome — rows read back, saveIfNotExists, collection mutation, counters, TTLs, soft-delete expiry — KandraTestcontainers. The fake returns no rows and applies nothing.
  • LWT conflict paths specifically (KandraOptimisticLockException, saveIfNotExists() == false) — Testcontainers only. There's no seam anywhere in the fake to force wasApplied() == false.
Tip

See /modules/kandra-test for the full API reference (both KandraRuntime classes, both repository() calling conventions — they differ, and mixing them up is a common copy-paste mistake), /tutorial/12-testing for both styles used on the tutorial's own todo app, and /battle-scars/testing-lwt-and-fakes for the incident this page is built on.