3

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?

Milo
  • 3,365
  • 9
  • 30
  • 44
Marcus Lanvers
  • 383
  • 5
  • 20

2 Answers2

7

You can use assertFailsWith from the Kotlin standard library:

assertFailsWith<MyRuntimeException> { myMethodThatThrowsThatException() }
yole
  • 92,896
  • 20
  • 260
  • 197
4

The assertThrows method expects a Class as its first parameter, but you're trying to give it a KClass. To fix this, just do the following (as described in the documentation here):

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

You can also leave out the explicit Executable type:

assertThrows(MyRuntimeException::class.java, { myMethodThatThrowsThatException() })

Or if your method really doesn't take any parameters, you can use a method reference to it:

assertThrows(MyRuntimeException::class.java, ::myMethodThatThrowsThatException)
zsmb13
  • 85,752
  • 11
  • 221
  • 226