Reputation: 411
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?
Upvotes: 3
Views: 5277
Reputation: 97138
You can use assertFailsWith from the Kotlin standard library:
assertFailsWith<MyRuntimeException> { myMethodThatThrowsThatException() }
Upvotes: 7
Reputation: 89548
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)
Upvotes: 4