要测试我的代码是否抛出预期的异常,我使用以下语法:
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)
您检查消息的语法错误。作为 bjfletcher 建议的替代方案,您还可以根据文档使用以下内容:
val thrown = the [IllegalArgumentException] thrownBy Algorithms.create(degree)
thrown.getMessage should equal ("<whatever the message is")
我个人更喜欢 bjfletcher 引入的第一个替代方案,因为它更紧凑。但是捕获异常本身为您提供了更多检查其内容的可能性。
| 归档时间: |
|
| 查看次数: |
3598 次 |
| 最近记录: |