Search code examples
scalascalatest

How to know when to use `a`, `an` or `the` in ScalaTest Matchers when asserting exceptions?


I am reading the section on Testing Exceptions on ScalaTest documentation and looking at examples such as

an [IndexOutOfBoundsException] should be thrownBy s.charAt(-1)

I tested a and that works too

a [IndexOutOfBoundsException] should be thrownBy s.charAt(-1)

and

val thrown = the [IndexOutOfBoundsException] thrownBy s.charAt(-1)

I am confused and there is little to no documentation about these keywords. Thanks


Solution

  • Unfortunately, scalatest docs aren't that detailed about that, but it's more or less like this:

    You should use a when you just want to assert on the type of exception thrown, but not it's contents (e.g. message, nested exception, etc.), but the implementation and behavior are otherwise identical

    You should use an when exception class starts with a vowel - just because of English spelling rules. Behind the scenes, they are represented by different machinery (AMatcher vs. AnMatcher), but behavior is virtually identical (the only difference I ever observed is the use of "a" vs. "an" in the failure message)

    You should use the when you want to assert on the type of exception thrown, and also capture the exception instance to perform additional assertions (on the message, nested exception, etc.)