11

I'm using ScalaTest for testing some Scala code. I currently testing for expected exceptions with code like this

import org.scalatest._
import org.scalatest.matchers.ShouldMatchers

class ImageComparisonTest extends FeatureSpec with ShouldMatchers{

    feature("A test can throw an exception") {

        scenario("when an exception is throw this is expected"){
            evaluating { throw new Exception("message") } should produce [Exception]
        }
    }
}

But I would like to add additional check on the exception, e.g. I would like to check that the exceptions message contains a certain String.

Is there a 'clean' way to do this? Or do I have to use a try catch block?

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348

3 Answers3

18

I found a solution

val exception = intercept[SomeException]{ ... code that throws SomeException ... }
// you can add more assertions based on exception here
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
9

You can do the same sort of thing with the evaluating ... should produce syntax, because like intercept, it returns the caught exception:

val exception =
  evaluating { throw new Exception("message") } should produce [Exception]

Then inspect the exception.

Bill Venners
  • 3,851
  • 2
  • 21
  • 8
  • It works and I like this syntax: it's in line with all of the "should be" for function results. – Jim Pivarski Sep 11 '13 at 03:21
  • `evaluating` is deprecated in 2.x and removed in 3.x. Deprecation docs advise using `an [Exception] should be thrownBy` instead. However 3.0.0-M14 returns an `Assertion`: `val ex: Assertion = an [Exception] should be thrownBy {throw new Exception("boom")}`. Is there a way to get back the `Exception` thrown? – kostja Dec 21 '15 at 12:55
4

If you need to further inspect an expected exception, you can capture it using this syntax:

val thrown = the [SomeException] thrownBy { /* Code that throws SomeException */ }

This expression returns the caught exception so that you can inspect it further:

thrown.getMessage should equal ("Some message")

you can also capture and inspect an expected exception in one statement, like this:

the [SomeException] thrownBy {
  // Code that throws SomeException
} should have message "Some message"
Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151