Kotest Exceptions

Explains assertions for testing exceptions in Kotlin.

Exceptions

Kotest provides several assertions for verifying exceptions.

Use shouldThrow to assert that a block throws an exception of the specified type.

shouldThrow<IllegalArgumentException> {
    // code that should throw IllegalArgumentException
}

The exception can also be captured and inspected.

val exception = shouldThrow<IllegalArgumentException> {
    // code that should throw IllegalArgumentException
}

exception.message shouldBe "expected message"

shouldThrow<T> also passes when the thrown exception is a subtype of T. If the exact exception type must match, use shouldThrowExactly.

shouldThrowExactly<IllegalArgumentException> {
    // code that should throw exactly IllegalArgumentException
}

If only the fact that some exception is thrown matters, use shouldThrowAny.

shouldThrowAny {
    // code that should throw any Throwable
}

References