exceptiontestingjunitkotlinunchecked-exception

How do I test expected Unchecked Exceptions in Kotlin?


I am trying to write a test in Kotlin that makes sure an unchecked exception is thrown in specific circumstances.

I am trying to use org.junit.jupiter.api.Assertions.assertThrows like this:

assertThrows(MyRuntimeException::class, Executable { myMethodThatThrowsThatException() })

when i try this i get a

Type inference failed compiler error

because my Exception in not a CheckedException but a RuntimeException. Is there any good way to test this behavior without doing the naive try catch?


Solution

  • You can use assertFailsWith from the Kotlin standard library:

    assertFailsWith<MyRuntimeException> { myMethodThatThrowsThatException() }