How to check advanced properties of expected exceptions with ScalaTest

I am using ScalaTest to test Scala code. I am currently testing 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 an additional exception check, for example. I would like to verify that the exception message contains a specific line.

Is there a "clean" way to do this? Or do I need to use a catch try block?

+7
scala exception testing scalatest
source share
3 answers

I found a solution

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

You can do the same with evaluation ... should generate syntax, because, like interception, it returns an excluded caught:

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

Then check the exception.

+9
source share

If you need to further check the expected exception, you can write it using this syntax:

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

This expression returns an thrown exception so you can further examine it:

 thrown.getMessage should equal ("Some message") 

you can also catch and check the expected exception in a single expression, for example:

 the [SomeException] thrownBy { // Code that throws SomeException } should have message "Some message" 
+2
source share

All Articles