12

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 

?

Łukasz Rzeszotarski
  • 5,791
  • 6
  • 37
  • 68

2 Answers2

26

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
bjfletcher
  • 11,168
  • 4
  • 52
  • 67
  • 3
    How would I check for a substring of the message? Assign the result of "the ... thrownBy ... " to a val, and then use regular matchers? – Dilum Ranatunga Nov 07 '15 at 01:05
  • 2
    If you want to assert on a substring, you can: ```(the [ArithmeticException] thrownBy 1 / 0).getMessage should include ("zero")``` – Michael Yakobi Oct 10 '18 at 12:52
7

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.

Visiedo
  • 377
  • 5
  • 9