开发者

How to test for additional properties of expected Exceptions using ScalaTest

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?


I found a solution

val exception = intercept[SomeException]{ ... code that throws SomeException ... }
// you can add more assertions based on exception here


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.


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜