如何使用ScalaTest测试预期异常的其他属性

时间:2010-11-21 11:47:55

标签: exception testing scala scalatest

我正在使用ScalaTest测试一些Scala代码。 我目前正在使用像这样的代码

测试预期的异常
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]
        }
    }
}

但我想在例外情况下添加额外的检查,例如我想检查一下例外消息是否包含某个字符串。

有没有'干净'的方法吗?或者我是否必须使用try catch块?

3 个答案:

答案 0 :(得分:17)

我找到了解决方案

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

答案 1 :(得分:9)

你可以用评估来做同样的事情......应该产生语法,因为像拦截一样,它会返回被捕获的异常:

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

然后检查异常。

答案 2 :(得分:2)

如果您需要进一步检查预期的异常,可以使用以下语法捕获它:

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

此表达式返回捕获的异常,以便您可以进一步检查它:

thrown.getMessage should equal ("Some message")

您还可以在一个语句中捕获并检查预期的异常,如下所示:

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