This document describes the testing approach used in vanilla Kotlin. The project uses integration tests to verify the full application stack against real external dependencies, and unit tests to verify business logic and service behavior in isolation.
Integration tests run the full application with real HTTP servers, databases, and Kafka brokers (via Docker Compose). Each application module has an AppTest class that starts the app and exercises its major workflows.
The API app test (apps/api/src/test/kotlin/vanillakotlin/api/AppTest.kt) mocks external services but tests against real HTTP and database:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class AppTest {
private val mockThingServer = MockThingServer()
private var app: App? = null
@BeforeEach fun beforeEach() {
// Clean up database before each test
val config = loadConfig<Config>()
val jdbi = createJdbi(config.db, mapper)
jdbi.useHandle<Exception> { handle ->
handle.execute("DELETE FROM favorite_thing")
}
}
@BeforeAll fun beforeAll() {
// Override the HTTP client baseUrl to the mocked server's address
withSystemProperties(
mapOf(
"config.override.http.client.thing.gateway.baseUrl" to "http://localhost:${mockThingServer.port}",
),
) {
app = App()
app?.start()
}
}
@AfterAll fun afterAll() {
mockThingServer.close()
app?.close()
}
@Test fun `health check ok`() {
val request = Request(Method.GET, "http://localhost:${app?.httpServerPort}/health")
val response = JavaHttpClient()(request)
response.status shouldBe Status.OK
}
}The test uses @BeforeAll to start the application once per class, and @BeforeEach to clean the database before each test. The @TestInstance(PER_CLASS) annotation enables instance-level setup; without it, @BeforeAll would require static access.
The Kafka transformer app test (apps/kafka-transformer/src/test/kotlin/vanillakotlin/kafkatransformer/AppTest.kt) demonstrates per-test resource isolation:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class AppTest {
private var app: App? = null
private lateinit var mockThingServer: MockWebServer
private lateinit var sourceTopicName: String
private lateinit var sinkTopicName: String
private val broker = if (System.getenv().containsKey("CI")) "kafka:9092" else "localhost:9092"
@BeforeEach fun beforeEach() {
// Fresh topic names and MockWebServer instance per test
// This prevents cross-test collisions from leftover topics/messages
sourceTopicName = randomString()
sinkTopicName = randomString()
val dispatcher: Dispatcher =
object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
return when (request.path?.substringBefore("?")) {
"/things/v4/graphql/compact/thing" -> MockResponse().setResponseCode(200).setBody(sampleThingGraphQlResponse)
else -> MockResponse().setResponseCode(404)
}
}
}
mockThingServer = MockWebServer()
mockThingServer.dispatcher = dispatcher
mockThingServer.start()
// Create topics synchronously before starting the app
AdminClient.create(mapOf("bootstrap.servers" to broker)).use { adminClient ->
adminClient.createTopics(
listOf(
NewTopic(sourceTopicName, 1, 1),
NewTopic(sinkTopicName, 1, 1),
),
).all().get()
}
val overriddenConfiguration = mapOf(
"config.override.http.client.thing.gateway.baseUrl" to "http://localhost:${mockThingServer.port}",
"config.override.kafka.consumer.topics" to sourceTopicName,
"config.override.kafka.producer.topic" to sinkTopicName,
)
withSystemProperties(overriddenConfiguration) {
app = App()
app?.start()
}
}
@AfterEach fun afterEach() {
app?.close()
mockThingServer.close()
}
@Test fun `the kafkatransformer should consume, process, and forward a valid message successfully`() {
val producer = KafkaProducer<String>(
config = KafkaProducer.Config(broker = broker, topic = sourceTopicName),
publishTimerMetric = metricsPublisher,
)
producer.start()
val userName = randomUsername()
producer.send(KafkaOutputMessage(key = "$userName:$thingIdentifier", value = thingIdentifier))
val receivedMessages = collectMessages(broker = broker, topic = sinkTopicName, metricsPublisher = metricsPublisher)
receivedMessages.size shouldBe 1
assertSoftly(receivedMessages.first()) {
this.key shouldBe "$userName:$thingIdentifier"
this.body shouldBe mapper.writeValueAsBytes(expectedUserFavoriteThing)
}
}
}This test uses @BeforeEach instead of @BeforeAll because MockWebServer cannot be restarted once closed. By creating fresh topics and a fresh mock server before each test, the tests avoid cross-test state pollution. This was a key fix to prevent flakiness in the test suite—prior to this change, tests would fail when run in sequence because previous test runs left topics behind.
The outbox processor test (apps/outbox-processor/src/test/kotlin/vanillakotlin/outboxprocessor/AppTest.kt) uses @BeforeAll because it doesn't need per-test resource recreation:
@Test fun `the outbox processor should pop and send successfully`() {
val messageKey = randomString()
val bodyString = randomString()
// Insert message into outbox table
jdbi.inTransaction<Unit, Exception> { handle ->
insertOutbox(handle, buildOutbox(messageKey = messageKey).copy(body = bodyString.toByteArray()))
}
// Verify message appears in Kafka topic
val receivedMessages = collectMessages(
broker = broker,
topic = sinkTopicName,
filter = { kafkaMessage -> kafkaMessage.key == messageKey },
stopWhen = { messages -> messages.size == 1 },
)
receivedMessages.size shouldBe 1
String(receivedMessages.first().body!!) shouldBe bodyString
// Verify message was removed from database
getRowCount(jdbi, messageKey) shouldBe 0
}This test verifies the outbox pattern: messages inserted into the database are picked up by the processor and forwarded to Kafka, then removed from the database.
Unit tests verify business logic without starting the full application or connecting to external services. Vanilla Kotlin uses functional injection (SAM interfaces) instead of mocking frameworks, making tests concise and readable.
The FavoriteThingsService test (apps/api/src/test/kotlin/vanillakotlin/api/favoritethings/FavoriteThingsServiceTest.kt) injects behavior via lambda functions:
@Test fun `saveFavoriteThing success`() {
val service = FavoriteThingsService(
upsertFavoriteThing = UpsertFavoriteThing { testFavorites[0] },
deleteFavoriteThingRepository = DeleteFavoriteThing { 1 },
findAllFavoriteThings = FindAllFavoriteThings { testFavorites },
getThingDetails = GetThingDetails { buildTestThing(it) },
)
val result = service.saveFavoriteThing(FavoriteThing(thingIdentifier = testThings[0]))
assertSoftly(result) {
this shouldBe SaveResult.Success
}
}
@Test fun `deleteFavoriteThing SQL Exception`() {
val service = FavoriteThingsService(
upsertFavoriteThing = UpsertFavoriteThing { testFavorites[0] },
deleteFavoriteThingRepository = DeleteFavoriteThing { throw SQLException("Failure") },
findAllFavoriteThings = FindAllFavoriteThings { testFavorites },
getThingDetails = GetThingDetails { thingId -> buildTestThing(thingId) },
)
val result = service.deleteFavoriteThing(testFavorites[0].thingIdentifier)
result shouldBe DeleteResult.Error(DeleteErrorType.DATABASE_ERROR)
}Each test injects the exact behavior needed. To test an error path, just throw the exception directly in the lambda—no need for mock setup boilerplate.
The bulk inserter handler test (apps/bulk-inserter/src/test/kotlin/vanillakotlin/bulkinserter/BulkInserterEventHandlerTest.kt) uses simple counters and collections instead of mocks:
@Test fun `a populated message should be added to the batch`() {
val batchCount = AtomicInteger(0)
val addedItems = mutableListOf<FavoriteThing>()
val runBatchCount = AtomicInteger(0)
val handler = BulkInserterHandler(
addToBatch = AddFavoriteThingToBatch { item ->
addedItems.add(item)
batchCount.incrementAndGet()
},
runBatch = RunFavoriteThingBatch {
runBatchCount.incrementAndGet()
1
},
)
handler.processSequence(
sequenceOf(
KafkaMessage(
// ... message details
body = mapper.writeValueAsBytes(userFavoriteThing),
),
),
)
assertSoftly {
batchCount.get() shouldBe 1
runBatchCount.get() shouldBe 1
addedItems.size shouldBe 1
addedItems[0].thingIdentifier shouldBe userFavoriteThing.thingIdentifier
}
}The handler is injected with callbacks that track behavior using mutable collections, making assertions simple and direct.
The repository test (libs/db/src/test/kotlin/vanillakotlin/db/repository/FavoriteThingRepositoryTest.kt) uses a real test database:
class FavoriteThingRepositoryTest {
private val jdbi by lazy { buildTestDb() }
private val repository by lazy { FavoriteThingRepository(jdbi) }
@Test fun `upsert favorite thing - insert new thing`() {
val favoriteThing = FavoriteThing(id = null, thingIdentifier = randomThing())
val result = repository.upsert(favoriteThing)
assertSoftly {
result.id shouldNotBe null
result.thingIdentifier shouldBe favoriteThing.thingIdentifier
result.createdTs shouldNotBe null
result.updatedTs shouldNotBe null
}
}
}The test uses buildTestDb() to create an in-memory or isolated test database, allowing tests to verify actual CRUD operations without mocking the database layer.
Integration tests rely on real external services defined in docker-compose.yml:
services:
kafka:
image: apache/kafka:3.8.1
container_name: kafka
hostname: kafka
ports:
- "9092:9092"
db:
image: postgres:15.8-alpine
container_name: vanilla-kotlin-db
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
ports:
- '5432:5432'
volumes:
- ./db-migration/initdb.d/:/docker-entrypoint-initdb.d
healthcheck:
test: ["CMD", "sh", "-c", "pg_isready -U $$POSTGRES_USER -h $$(hostname -i)"]
interval: 5s
timeout: 5s
retries: 5Before running integration tests, start Docker Compose:
docker-compose up -d
./gradlew :db-migration:flywayMigrateTests detect the environment with a simple check:
private val broker = if (System.getenv().containsKey("CI")) "kafka:9092" else "localhost:9092"In CI environments (which run Docker services by hostname), tests connect to kafka:9092. Locally, they connect to localhost:9092.
Dynamic resource creation prevents test interference. Kafka topics and mock server instances are created fresh per test where needed (as in the Kafka transformer test), ensuring that leftover state from a previous test run cannot affect the current one. Database tables are truncated or tests use isolated databases (see buildTestDb()). Random test data (via randomString(), randomThing(), etc.) makes it safe to run tests in parallel without hard-coded value collisions.
Configuration overrides via withSystemProperties() allow tests to inject their own topic names, base URLs, and other settings without modifying application code:
withSystemProperties(
mapOf(
"config.override.kafka.consumer.topics" to sourceTopicName,
"config.override.kafka.producer.topic" to sinkTopicName,
)
) {
app = App()
app?.start()
}Run all tests:
./gradlew testRun tests for a single module:
./gradlew :apps:api:test
./gradlew :libs:kafka:testRun only integration tests (AppTest classes):
./gradlew test --tests "*AppTest"Run only unit tests (non-AppTest classes):
./gradlew test --tests "*ServiceTest" --tests "*HandlerTest" --tests "*RepositoryTest"Vanilla Kotlin tests use integration tests to verify full application workflows against real external dependencies, and unit tests to verify service and repository behavior using functional injection. This approach catches integration issues early while keeping unit tests fast and maintainable. The per-test resource isolation pattern (fresh Kafka topics, fresh mock servers, database cleanup) prevents cross-test failures and enables safe parallel test execution.