Kandra

12. Testing

kandra-test gives you two ways to test code that uses Kandra, and they are not interchangeable — one is fast and structural, the other is slower and real. Picking the wrong one for a given assertion either wastes a container spin-up on a check that didn't need it, or — worse — gives you a green test that never actually exercised the behavior you think it did.

build.gradle.kts
dependencies {
    testImplementation("com.kandraorm.kandra:kandra-test:0.5.2")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")          // kandra-test doesn't bring JUnit
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
 
tasks.test { useJUnitPlatform() }
On 0.5.0 and earlier

Since 0.5.1 kandra-test brings the DataStax driver along, KandraTestUtils.reset() replaces SchemaRegistry.clear() (no @OptIn(InternalKandraApi::class)), and FakeKandraSession.capturedBatchViews() returns each statement's CQL and bound values as a public CapturedStatement (#179, #180, #181). On 0.5.0, add testImplementation("com.datastax.oss:java-driver-core:4.17.0") and use @OptIn(InternalKandraApi::class) with SchemaRegistry.clear().

FakeKandraSession — structure, not outcomes

FakeKandraSession's own doc comment describes it as the way to "wire a full repository stack without Testcontainers" and assert on structural behavior — did a batch collect the right statements, is the shape right. That is exactly what you want for verifying page 06's KandraBatchScope call actually produces two INSERTs, or page 07's update() actually issues an IF version = ? clause: the real repository, StatementBuilder and BatchEngine code runs, and the statements it builds are captured.

What the fake cannot do — verified from source

FakeKandraSession.execute() always returns an empty result set with wasApplied() == true, and FakeBoundStatement does no CQL type encoding and stores no rows. So it can show you what was built, never what the database did with it. There is no seam to make an LWT appear to fail, so saveIfNotExists() == false and a KandraOptimisticLockException conflict — the two things page 07's whole optimistic-locking story depends on — cannot be produced through it. That is tracked, deliberately, as ISS-020 — a documented limitation, not a bug someone forgot to fix. ISS-020's own takeaway, stated plainly in the issue: "don't read '43 unit tests passing' as evidence that LWT/optimistic-locking/collection mutation paths work — they are exercised for the first time by the Testcontainers suite."

Older versions threw here

Before 0.4.7 (GH #28 / ISS-040), FakePreparedStatement.bind(...) unconditionally threw UnsupportedOperationException, so any repository call failed immediately under KandraTestUtils.inMemory(...). That is fixed; this page used to carry a test asserting the throw, which would now fail.

So what is the fake good for? Asserting on the statements a repository call builds. inMemory(...) wires its own FakeKandraSession — read it back from runtime.session:

import io.kandra.test.FakeKandraSession
import io.kandra.test.KandraTestUtils
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals
 
class TodoSaveStructureTest {
 
    @AfterEach
    fun tearDown() = KandraTestUtils.reset()   // schema registration is process-global
 
    @Test
    fun `save builds one LOGGED batch with the primary INSERT`() {
        val runtime = KandraTestUtils.inMemory(Todo::class)
        val session = runtime.session as FakeKandraSession
        val todoRepo = runtime.repository(Todo::class)
 
        todoRepo.save(Todo(UUID.randomUUID(), Instant.now(), UUID.randomUUID(), "Ship the release", null))
 
        val batch = session.capturedBatchViews().single()          // List<CapturedStatement(cql, values)>
        assertEquals(1, batch.size)
        assertEquals(true, batch.single().cql.startsWith("INSERT INTO todos "))
 
        runtime.close()
    }
}

The bound values themselves are available through FakeBoundStatement.boundValues(), but that class is internal to kandra-test, so from your own module assert on the public driver API as above.

KandraTestcontainers — where LWT, atomicity, and soft-delete timing actually get exercised

KandraTestcontainers.freshKeyspace(...) spins up a real cassandra:4.1 container (shared across the JVM run, one fresh keyspace per call) and hands you the production KandraRuntime — the same class Ktor installs, not a test double. Everything below is a real round trip against real CQL semantics: real IF version = ? LWT evaluation, real LOGGED BATCH atomicity, real TTL writes.

build.gradle.kts
dependencies {
    testImplementation("org.testcontainers:cassandra:1.21.4")     // 0.5.1: required; kandra-test brings it since 0.5.2 (#190)
    testImplementation("org.testcontainers:junit-jupiter:1.21.4")
}

Test 1 — the optimistic-lock conflict from page 07

import io.kandra.test.KandraTestcontainers
import io.kandra.core.exception.KandraOptimisticLockException
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.*
import java.time.Instant
import java.util.UUID
 
class TodoOptimisticLockIntegrationTest {
 
    private val db = KandraTestcontainers.freshKeyspace(User::class, Todo::class)
    private val todoRepo = db.suspendRepository<Todo>()
 
    @AfterEach
    fun tearDown() = db.close()
 
    @Test
    fun `updating from a stale snapshot throws KandraOptimisticLockException`() = runTest {
        val ownerId = UUID.randomUUID()
        val createdAt = Instant.now()
        val todoId = UUID.randomUUID()
        val todo = Todo(ownerId, createdAt, todoId, "Ship the release", null)
        todoRepo.save(todo)
 
        // Two "concurrent" readers both load the same version-1 snapshot.
        val readerA = todoRepo.findById(ownerId, createdAt, todoId)!!
        val readerB = todoRepo.findById(ownerId, createdAt, todoId)!!
 
        todoRepo.update(readerA, readerA.copy(title = "Ship the release (edited by A)"))  // wins, version -> 2
 
        // B still holds version 1 — its update loses the race.
        assertThrows<KandraOptimisticLockException> {
            todoRepo.update(readerB, readerB.copy(title = "Ship the release (edited by B)"))
        }
    }
}

This is precisely the scenario FakeKandraSession cannot produce — wasApplied() is hardcoded true under the fake, so this exact assertion would never see a failure to catch. Against the real container, the second update() issues UPDATE ... IF version = 1 for real, ScyllaDB/Cassandra evaluates it against the real (now version = 2) row, and [applied] genuinely comes back false.

Test 2 — soft-delete timing from page 08

class TodoSoftDeleteIntegrationTest {
 
    private val db = KandraTestcontainers.freshKeyspace(User::class, Todo::class)
    private val todoRepo = db.suspendRepository<Todo>()
 
    @AfterEach
    fun tearDown() = db.close()
 
    @Test
    fun `delete rewrites the row with a TTL marker instead of a real DELETE`() = runTest {
        val ownerId = UUID.randomUUID()
        val createdAt = Instant.now()
        val todoId = UUID.randomUUID()
        val todo = Todo(ownerId, createdAt, todoId, "Renew passport", null)
        todoRepo.save(todo)
 
        todoRepo.delete(todo)   // @SoftDelete: UPDATE ... USING TTL 604800, not DELETE
 
        // A real DELETE would make this null immediately. It doesn't, here.
        val afterDelete = todoRepo.findById(ownerId, createdAt, todoId)
        assertNotNull(afterDelete)
        assertTrue(afterDelete!!.isDeleted)
        assertEquals("Renew passport", afterDelete.title)   // whole row rewritten with a fresh TTL, not just a marker column
    }
}

This is the assertion FakeKandraSession categorically cannot make either — it has no notion of a row existing after a write, since execute() always returns an empty result set regardless of what was "saved." Only a real backing store can show you that the row is still there, still readable, still carrying its real data, right after delete() — which is exactly the property @SoftDelete depends on.

Test 3 — denormalized-write atomicity from page 06

import io.kandra.core.ExperimentalKandraApi
 
class DenormalizedWriteAtomicityIntegrationTest {
 
    private val db = KandraTestcontainers.freshKeyspace(User::class, Todo::class, TodoByAssignee::class)
    private val todoRepo = db.suspendRepository<Todo>()
    private val byAssigneeRepo = db.suspendRepository<TodoByAssignee>()
 
    @AfterEach
    fun tearDown() = db.close()
 
    @OptIn(ExperimentalKandraApi::class)
    @Test
    fun `assigning a todo writes both tables atomically via KandraBatchScope`() = runTest {
        val ownerId = UUID.randomUUID()
        val assigneeId = UUID.randomUUID()
        val createdAt = Instant.now()
        val todoId = UUID.randomUUID()
 
        db.runtime.batch {
            todoRepo.saveInBatch(Todo(ownerId, createdAt, todoId, "Review PR", assigneeId))
            byAssigneeRepo.saveInBatch(TodoByAssignee(assigneeId, createdAt, todoId, ownerId, "Review PR"))
        }
 
        assertEquals(todoId, todoRepo.findById(ownerId, createdAt, todoId)?.todoId)
        assertEquals(todoId, byAssigneeRepo.findById(assigneeId, createdAt, todoId)?.todoId)
    }
}

Both writes landing (or, if you kill the container mid-batch in a more elaborate failure-injection test, both not landing) is the actual atomicity guarantee LOGGED BATCH provides — and it's only observable against something that actually executes CQL. FakeKandraSession can show that the batch was built with both INSERTs, but it cannot show that the database applied them atomically — per ISS-020, above.

The dividing line, stated plainly

QuestionTool
"Did my code call saveInBatch on the two repos I expected, in the right order?"FakeKandraSession
"Does marking a todo done twice concurrently actually conflict?"KandraTestcontainers
"Does soft-deleting a todo leave it readable until the TTL, not gone immediately?"KandraTestcontainers
"Does the denormalized write from page 06 really land both rows atomically?"KandraTestcontainers
"Is this CQL string what I think it is?"Either — FakeKandraSession is faster when you only need to see the statement, not its effect

Anything touching LWT, real row state after a write, or cross-table atomicity: reach for KandraTestcontainers. It's slower — the shared container's first access in a test run blocks on a cold pull/start — but it's the only one of the two that's telling you the truth.

Next: /tutorial/13-migrations — the app ships, and now a real schema change has to go out without taking the keyspace down or double-applying under a rolling deploy.