【问题标题】:How to test for additional properties of expected Exceptions using ScalaTest如何使用 ScalaTest 测试预期异常的附加属性
【发布时间】:2011-05-13 08:48:14
【问题描述】:

我正在使用 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 块?

【问题讨论】:

    标签: exception testing scala scalatest


    【解决方案1】:

    我找到了解决办法

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

    【讨论】:

      【解决方案2】:

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

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

      然后检查异常。

      【讨论】:

      • 它有效,我喜欢这种语法:它符合函数结果的所有“应该”。
      • evaluating 在 2.x 中已弃用并在 3.x 中删除。弃用文档建议改用an [Exception] should be thrownBy。但是 3.0.0-M14 返回 Assertion: val ex: Assertion = an [Exception] should be thrownBy {throw new Exception("boom")}。有没有办法找回被抛出的Exception
      【解决方案3】:

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

      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"
      

      【讨论】:

      • 这很好地遵循了现有的非异常测试模式。太棒了。
      猜你喜欢
      • 2015-08-09
      • 2011-07-31
      • 1970-01-01
      • 2019-01-23
      • 2016-05-27
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      相关资源
      最近更新 更多