Kotest Deep Dive: Spec Styles, Matchers, and Data-Driven Tests
Kotest is the most powerful Kotlin-native testing framework, offering multiple spec styles, a rich matcher library, soft assertions, and property-based testing. This guide covers everything from choosing a spec style to writing data-driven tests with lifecycle hooks.
Kotest is not just "JUnit but with Kotlin syntax". It is a full testing framework built specifically for Kotlin, designed to take advantage of the language's features: coroutines, extension functions, DSLs, and sealed classes. Once you switch to Kotest, going back feels like downgrading.
This post covers the parts that matter most: spec styles, the matcher library, soft assertions, data-driven tests, and lifecycle hooks.
Setting Up Kotest
Add the dependencies to your build.gradle.kts:
dependencies {
testImplementation("io.kotest:kotest-runner-junit5:5.9.1")
testImplementation("io.kotest:kotest-assertions-core:5.9.1")
testImplementation("io.kotest:kotest-property:5.9.1")
testImplementation("io.kotest:kotest-framework-datatest:5.9.1")
}
tasks.withType<Test> {
useJUnitPlatform()
}For Android projects, use the kotest-runner-junit5 variant and ensure you have testOptions { unitTests.isReturnDefaultValues = true } in your Android block.
Choosing a Spec Style
Kotest offers seven spec styles. The right one depends on your team and what you are testing.
DescribeSpec
DescribeSpec mirrors the describe/it pattern from RSpec and Jest. It is the best choice when your team comes from a JavaScript or Ruby background, or when you are testing a class with multiple methods.
class UserServiceTest : DescribeSpec({
val repository = mockk<UserRepository>()
val service = UserService(repository)
describe("UserService") {
describe("findById") {
it("returns the user when found") {
val user = User(id = 1, name = "Alice", email = "alice@example.com")
every { repository.findById(1) } returns user
val result = service.findById(1)
result shouldBe user
}
it("throws NotFoundException when user does not exist") {
every { repository.findById(99) } returns null
shouldThrow<NotFoundException> {
service.findById(99)
}
}
}
describe("create") {
it("saves and returns the new user") {
val newUser = User(id = 0, name = "Bob", email = "bob@example.com")
val savedUser = newUser.copy(id = 42)
every { repository.save(newUser) } returns savedUser
val result = service.create(newUser)
result.id shouldBe 42
verify(exactly = 1) { repository.save(newUser) }
}
}
}
})BehaviorSpec
BehaviorSpec enforces a given/when/then structure. Use it when you want the tests themselves to act as living documentation.
class OrderProcessorTest : BehaviorSpec({
val paymentGateway = mockk<PaymentGateway>()
val processor = OrderProcessor(paymentGateway)
given("an order with a valid payment method") {
val order = Order(
id = "ORD-001",
amount = 99.99,
paymentMethod = PaymentMethod.CARD
)
`when`("the order is processed") {
every { paymentGateway.charge(order.amount, order.paymentMethod) } returns PaymentResult.SUCCESS
val result = processor.process(order)
then("it should return a confirmed status") {
result.status shouldBe OrderStatus.CONFIRMED
}
then("it should have a non-null transaction ID") {
result.transactionId shouldNotBe null
}
}
}
given("an order with an expired card") {
val order = Order(
id = "ORD-002",
amount = 50.00,
paymentMethod = PaymentMethod.CARD
)
`when`("the order is processed") {
every { paymentGateway.charge(order.amount, order.paymentMethod) } returns PaymentResult.DECLINED
val result = processor.process(order)
then("it should return a failed status") {
result.status shouldBe OrderStatus.FAILED
}
}
}
})FunSpec
FunSpec is the closest to JUnit. It is simple and familiar. Use it for utility functions or when you want minimal overhead.
class StringExtensionsTest : FunSpec({
test("truncate shortens strings longer than the limit") {
"Hello, World!".truncate(5) shouldBe "Hello..."
}
test("truncate returns the original string when shorter than limit") {
"Hi".truncate(10) shouldBe "Hi"
}
test("toSlug converts spaces to hyphens and lowercases") {
"Hello World".toSlug() shouldBe "hello-world"
}
})The Matcher Library
Kotest's matcher library is one of its strongest features. The infix syntax reads like English.
Collection Matchers
val items = listOf("apple", "banana", "cherry")
items shouldHaveSize 3
items shouldContain "banana"
items shouldContainAll listOf("apple", "cherry")
items shouldNotContain "mango"
items.shouldBeUnique()
items shouldContainInOrder listOf("apple", "banana")
// For maps
val scores = mapOf("Alice" to 95, "Bob" to 87)
scores shouldContainKey "Alice"
scores shouldContainValue 95
scores["Alice"] shouldBe 95Exception Matchers
// Assert exception type and message
val exception = shouldThrow<IllegalArgumentException> {
parseAge(-5)
}
exception.message shouldContain "must be positive"
// shouldThrowAny captures any exception
val anyEx = shouldThrowAny {
riskyOperation()
}
anyEx.shouldBeInstanceOf<RuntimeException>()
// Assert no exception is thrown
shouldNotThrow<Exception> {
safeOperation()
}Numeric Matchers
val price = 9.99
price shouldBe (9.99 plusOrMinus 0.001)
price shouldBeGreaterThan 5.0
price shouldBeLessThan 20.0
price.shouldBeBetween(5.0, 15.0, 0.001)Soft Assertions
By default, a Kotest assertion stops the test on first failure. With assertSoftly, all assertions are collected and reported together. This is invaluable when validating response objects with many fields.
data class ApiResponse(
val status: Int,
val body: String,
val headers: Map<String, String>,
val duration: Long
)
class ApiIntegrationTest : DescribeSpec({
describe("POST /api/users") {
it("returns a valid response with all expected fields") {
val response = apiClient.post("/api/users", CreateUserRequest("Alice"))
assertSoftly(response) {
status shouldBe 201
body shouldContain "\"id\""
headers shouldContainKey "Content-Type"
headers["Content-Type"] shouldContain "application/json"
duration shouldBeLessThan 500L
}
}
}
})If status is 500 and duration is 2000ms, you see both failures reported in one run — not just the first one. This dramatically reduces the feedback cycle when debugging.
Data-Driven Tests
Data-driven tests (also called parameterized tests) let you run the same test logic with many different inputs. Kotest has first-class support via the datatest module.
class PasswordValidatorTest : FunSpec({
data class TestCase(
val password: String,
val expectedValid: Boolean,
val expectedError: String?
)
withData(
TestCase("short", false, "at least 8 characters"),
TestCase("nouppercase1!", false, "one uppercase letter"),
TestCase("NOLOWERCASE1!", false, "one lowercase letter"),
TestCase("NoSpecialChar1", false, "one special character"),
TestCase("ValidPass1!", true, null),
TestCase("Another$Valid9", true, null),
) { (password, expectedValid, expectedError) ->
val result = PasswordValidator.validate(password)
result.isValid shouldBe expectedValid
if (expectedError != null) {
result.errors shouldContain expectedError
}
}
})Kotest generates a descriptive test name from the TestCase.toString(). If you add a name property or override toString(), you get even clearer output:
data class TestCase(
val name: String,
val input: String,
val expected: Int
) : WithDataTestName {
override fun dataTestName() = name
}
withData(
TestCase("empty string returns 0", "", 0),
TestCase("single word counts 1", "hello", 1),
TestCase("multiple words count correctly", "hello world foo", 3),
) { (_, input, expected) ->
wordCount(input) shouldBe expected
}Lifecycle Hooks
Kotest gives you fine-grained control over test lifecycle through beforeTest, afterTest, beforeSpec, afterSpec, and beforeEach/afterEach (in specs that support them).
class DatabaseIntegrationTest : DescribeSpec({
val db = TestDatabase.create()
beforeSpec {
db.runMigrations()
}
afterSpec {
db.dropAll()
db.close()
}
beforeEach {
db.beginTransaction()
}
afterEach {
db.rollbackTransaction()
}
describe("UserRepository") {
val repo = UserRepository(db.connection)
it("saves a new user") {
val user = User(name = "Alice", email = "alice@test.com")
val saved = repo.save(user)
saved.id shouldBeGreaterThan 0
repo.findById(saved.id) shouldBe saved
}
it("finds users by email") {
repo.save(User(name = "Bob", email = "bob@test.com"))
repo.save(User(name = "Carol", email = "carol@test.com"))
val result = repo.findByEmail("bob@test.com")
result shouldNotBe null
result!!.name shouldBe "Bob"
}
}
})Project-Level Configuration
For global hooks that apply to every spec in the project, create a KotestProjectConfig:
// src/test/kotlin/TestConfig.kt
class TestConfig : AbstractProjectConfig() {
override val parallelism = 4
override suspend fun beforeAll() {
// Start test containers, seed global data
TestContainers.startAll()
}
override suspend fun afterAll() {
TestContainers.stopAll()
}
override fun extensions() = listOf(
SpringExtension,
AllureKotest
)
}Property-Based Testing
Kotest includes a property testing module that generates random inputs and checks invariants. It is excellent for finding edge cases you would never think to write by hand.
class JsonSerializerPropertyTest : StringSpec({
"serialization is idempotent for all valid users" {
forAll(
Arb.bind(
Arb.string(1..50),
Arb.email(),
Arb.int(18..120)
) { name, email, age ->
User(name = name, email = email, age = age)
}
) { user ->
val json = JsonSerializer.toJson(user)
val deserialized = JsonSerializer.fromJson<User>(json)
deserialized shouldBe user
}
}
"word count is never negative for any string" {
forAll(Arb.string()) { input ->
wordCount(input) >= 0
}
}
})Putting It All Together
Here is a realistic test for a service layer that combines everything:
class ProductServiceTest : DescribeSpec({
val repo = mockk<ProductRepository>()
val cache = mockk<CacheService>()
val service = ProductService(repo, cache)
beforeEach {
clearMocks(repo, cache)
}
describe("getProduct") {
context("when product is in cache") {
it("returns cached product without hitting repository") {
val product = Product(id = 1, name = "Widget", price = 9.99)
every { cache.get("product:1") } returns product
val result = service.getProduct(1)
assertSoftly(result) {
this shouldBe product
}
verify(exactly = 0) { repo.findById(any()) }
}
}
context("when product is not in cache") {
it("fetches from repository and caches the result") {
val product = Product(id = 2, name = "Gadget", price = 49.99)
every { cache.get("product:2") } returns null
every { repo.findById(2) } returns product
every { cache.set("product:2", product, any()) } just Runs
val result = service.getProduct(2)
result shouldBe product
verify(exactly = 1) { repo.findById(2) }
verify(exactly = 1) { cache.set("product:2", product, any()) }
}
}
}
})Key Takeaways
- Pick a spec style and stick to it per team.
DescribeSpecworks well for class-level tests;BehaviorSpecfor acceptance tests;FunSpecfor utilities. - Use
assertSoftlyfor any test that validates more than two fields. The time you save debugging is worth it. withDatareplaces copy-pasted tests. If you have two tests that differ only in their inputs, that's a sign to use data-driven testing.- Put database setup in
beforeSpec, transaction rollback inafterEach. Each test gets a clean slate without recreating the schema. - Property-based tests find the bugs you didn't know to look for. Add them for any pure function that processes user input.
Kotest rewards you more the more deeply you use it. The initial investment in learning the DSL pays off quickly when you have a test suite that is fast, readable, and thorough.