Throws Exception Testing

Additional Verification

You can capture the exception returned by shouldThrow or shouldThrowExactly and perform additional assertions on it.

    val exception = shouldThrow<IllegalArgumentException> {
        throw IllegalArgumentException("Invalid argument")
    }
    exception.message shouldBe "Invalid argument"

Summary

  • Use shouldThrow for checking a type or its subclass.
  • Use shouldThrowExactly for strict type matching.
  • Capture the thrown exception to validate its properties like the message or custom fields.