Łukasz Rzeszotarski
Łukasz Rzeszotarski

Reputation: 6140

ScalaTest thrownBy testing exception message

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

Answers (2)

Visiedo
Visiedo

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:

  1. Capture the exception and assign it to a val

val thrown = the [IllegalArgumentException] thrownBy Algorithms.create(degree)

  1. Use the val to inspect its contents. E.g.:

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

bjfletcher
bjfletcher

Reputation: 11518

Documentation:

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

Related Questions