O'Reilly logo

Scala Test-Driven Development by Gaurav Sood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required