Reputation: 6140
To test if my code is throwing expected exception I use the following syntax:
an [IllegalArgumentException] should be thrownBy(Algorithms.create(degree))
is there any way to test if thrown exception contains expected message like:
an [IllegalArgumentException(expectedMessage)] should be thrownBy(Algorithms.create(degree)) -- what doesn't compile
?
Upvotes: 16
Views: 18472
Reputation: 387
Your syntax for checking the message is wrong. As an alternative to what bjfletcher suggested, you can also use the following, as per the documentation:
val thrown = the [IllegalArgumentException] thrownBy Algorithms.create(degree)
thrown.getMessage should equal ("<whatever the message is")
I personally like the first alternative introduced by bjfletcher more, since it is more compact. But capturing the exception itself, gives you more possibilities to inspect its contents.
Upvotes: 9
Reputation: 11518
the [ArithmeticException] thrownBy 1 / 0 should have message "/ by zero"
and using that example:
the [IllegalArgumentException] thrownBy(Algorithms.create(degree)) should have message expectedMessage
Upvotes: 33