Intercepting exceptions

Sometimes, we need to test if the code is throwing an expected exception. This can be tested in JUnit style as used in the test for Decimal, for example:

try {
  Decimal("XYZ") 
} 
catch {
  case e:IllegalArgumentException => 
  assert(e.getMessage == "requirement failed: 
  Unable to convert string to number")   
  case _ =>fail 
}

Alternatively, it can be tested using intercept, for example:

intercept[IllegalArgumentException] {
  Binary("XYZ")

Both intercept and try…catch have their own advantages as evident from our implementation. try…catch allows access to the exception object for inspection, whereas intercept is more succinct.

All the tests in BeanSpec and BinaryToDecimalSpec will fail, and then we will fix these one at a time. Here is our ...

Get Scala Test-Driven Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.