kotlinintermediate
Testing with Kotest and Assertions
Write expressive tests with Kotest: string spec, data-driven tests, property-based testing, and matchers.
kotlinPress ⌘/Ctrl + Shift + C to copy
import io.kotest.core.spec.style.StringSpec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.kotest.matchers.string.shouldContain
import io.kotest.matchers.string.shouldStartWith
import io.kotest.matchers.collections.shouldContainAll
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.ints.shouldBeGreaterThan
import io.kotest.assertions.throwables.shouldThrow
class CalculatorTest : StringSpec({
"addition should work" {
(2 + 3) shouldBe 5
}
"string matchers" {
val greeting = "Hello, World!"
greeting shouldStartWith "Hello"
greeting shouldContain "World"
greeting.length shouldBeGreaterThan 5
}
"collection matchers" {
val list = listOf(1, 2, 3, 4, 5)
list shouldHaveSize 5
list shouldContainAll listOf(2, 4)
list.first() shouldBe 1
}
"exception testing" {
val ex = shouldThrow<IllegalArgumentException> {
require(false) { "Invalid input" }
}
ex.message shouldBe "Invalid input"
}
"nullable matchers" {
val value: String? = "hello"
value shouldNotBe null
val empty: String? = null
empty shouldBe null
}
})
class FizzBuzzTest : FunSpec({
fun fizzBuzz(n: Int): String = when {
n % 15 == 0 -> "FizzBuzz"
n % 3 == 0 -> "Fizz"
n % 5 == 0 -> "Buzz"
else -> n.toString()
}
test("non-multiples return number") {
listOf(1, 2, 4, 7, 8).forEach {
fizzBuzz(it) shouldBe it.toString()
}
}
test("multiples of 3 return Fizz") {
fizzBuzz(3) shouldBe "Fizz"
fizzBuzz(9) shouldBe "Fizz"
}
test("multiples of 15 return FizzBuzz") {
fizzBuzz(15) shouldBe "FizzBuzz"
fizzBuzz(30) shouldBe "FizzBuzz"
}
})Use Cases
- Expressive Kotlin unit testing
- Data-driven parameterized tests
- Collection and string assertion patterns
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
kotlinintermediate
Testing with JUnit 5 and Kotlin
Write expressive tests in Kotlin: JUnit 5, nested tests, parameterized tests, and extension functions.
Best for: Unit testing Kotlin classes and functions
#kotlin#testing
kotlinintermediate
Testing with MockK Framework
Mock dependencies in Kotlin tests with MockK: relaxed mocks, verify, coEvery, and slot captures.
Best for: Unit testing with mocked dependencies
#kotlin#testing
kotlinbeginner
Null Safety — Elvis, Safe Call, and let
Master Kotlin null safety: safe calls, Elvis operator, let/also scoping, and smart casts.
Best for: Safe navigation through nullable chains
#kotlin#null-safety
kotlinbeginner
Data Classes — Copy, Destructure, and Equals
Use data classes for immutable models: auto-generated equals, hashCode, copy, and destructuring.
Best for: Immutable domain models and DTOs
#kotlin#data-class