抛出ScalaTest测试异常消息

Łuk*_*ski 1 scala scalatest

要测试我的代码是否抛出预期的异常,我使用以下语法:

  an [IllegalArgumentException] should be thrownBy(Algorithms.create(degree))
Run Code Online (Sandbox Code Playgroud)

有没有办法测试抛出的异常是否包含预期的消息,如:

  an [IllegalArgumentException(expectedMessage)] should be thrownBy(Algorithms.create(degree)) -- what doesn't compile 
Run Code Online (Sandbox Code Playgroud)

bjf*_*her 12

文件:

the [ArithmeticException] thrownBy 1 / 0 should have message "/ by zero"
Run Code Online (Sandbox Code Playgroud)

并使用该示例:

 the [IllegalArgumentException] thrownBy(Algorithms.create(degree)) should have message expectedMessage
Run Code Online (Sandbox Code Playgroud)

  • 我如何检查消息的子字符串?将"the ... thrownBy ..."的结果分配给val,然后使用常规匹配器? (2认同)
  • 如果你想在子字符串上断言,你可以: ```(the [ArithmeticException] throwBy 1 / 0).getMessage should include ("zero")``` (2认同)

Vis*_*edo 6

您检查消息的语法错误。作为 bjfletcher 建议的替代方案,您还可以根据文档使用以下内容:

  1. 捕获异常并将其分配给一个 val

val thrown = the [IllegalArgumentException] thrownBy Algorithms.create(degree)

  1. 使用 val 检查其内容。例如:

thrown.getMessage should equal ("<whatever the message is")

我个人更喜欢 bjfletcher 引入的第一个替代方案,因为它更紧凑。但是捕获异常本身为您提供了更多检查其内容的可能性。