kotlinintermediate

Testing with Kotest and Assertions

Write expressive tests with Kotest: string spec, data-driven tests, property-based testing, and matchers.

kotlin
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.