【问题标题】:How to Display exception thrown in "should produce [exception]” in ScalaTest如何在ScalaTest中显示“应该产生[异常]”中抛出的异常
【发布时间】:2012-09-21 01:27:32
【问题描述】:

我想显示 Scala 测试中抛出的异常消息。

 " iWillThrowCustomException Method Failure test.   
 " should "Fail, Reason: Reason for failing. " in {
 evaluating {
      iWillThrowCustomException();
   } should produce [CustomException]
}

如果 CustomExeption 会针对不同的输入抛出不同类型的消息,比如说

(对于 -ve 金额 - 金额小于零,对于金额中的字符 - 无效金额)

如何显示在块中抛出的消息,因为它会通过 CustomException ,它会显示测试成功,但它已经抛出了错误

【问题讨论】:

    标签: scala


    【解决方案1】:

    您也可以查看intercept:

    val ex = intercept[CustomException] {
        iWillThrowCustomException()
    }
    ex.getMessage should equal ("My custom message")
    

    【讨论】:

      【解决方案2】:

      evaluating 也会返回一个异常,以便您检查它或打印消息。这是来自ScalaDoc 的示例:

      val thrown = evaluating { s.charAt(-1) } should produce [IndexOutOfBoundsException]
      thrown.getMessage should equal ("String index out of range: -1")
      

      据我所知,您不能在测试名称中包含异常消息。


      你可以做的是添加关于测试的附加信息info()

      "iWillThrowCustomException Method Failure test." in {
          val exception = evaluating { iWillThrowCustomException() } should produce [CustomException]
          info("Reason: " + exception.getMessage)
      }
      

      这将在测试结果中显示为嵌套消息。您可以找到有关此in ScalaDoc 的更多信息。

      【讨论】:

      • 非常感谢,这正是我想要的。
      猜你喜欢
      • 2011-10-23
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多