Kotest Testing Exceptions

This page explains exception testing in Kotest.

Testing Exceptions in Kotest

With Kotest, you can easily test exceptions:

package com.devkuma.kotest.tutorial.exceptions

import io.kotest.assertions.throwables.shouldNotThrow
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe

class ExceptionTest : FreeSpec({

    "exception test" - {
        "when an exception is thrown" {
            // Run code that throws an exception and catch that exception.
            val errorProneFunction: () -> Unit = {
                throw IllegalArgumentException("Exception occurred!")
            }
            val exception = shouldThrow<IllegalArgumentException> {
                errorProneFunction()
            }

            // The test passes when the expected exception is thrown.
            exception.message shouldBe "Exception occurred!"
        }

        "when no exception is thrown" {
            // Run code that does not throw an exception and verify that no exception is thrown.
            val safeFunction: () -> Unit = {}
            val exception = shouldNotThrow<IllegalArgumentException> {
                safeFunction()
            }

            // The test passes when no exception is thrown.
            exception shouldBe null
        }
    }
})

References