如何使用 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 块吗?
I'm using ScalaTest for testing some Scala code.
I currently testing for expected exceptions with code like this
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]
}
}
}
But I would like to add additional check on the exception, e.g. I would like to check that the exceptions message contains a certain String.
Is there a 'clean' way to do this? Or do I have to use a try catch block?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我找到了解决方案
I found a solution
您可以使用评估...应该生成语法做同样的事情,因为像拦截一样,它返回捕获的异常:
然后检查异常。
You can do the same sort of thing with the evaluating ... should produce syntax, because like intercept, it returns the caught exception:
Then inspect the exception.
如果需要进一步检查预期的异常,可以使用以下语法捕获它:
此表达式返回捕获的异常,以便您可以进一步检查它:
您还可以在一条语句中捕获并检查预期的异常,如下所示:
If you need to further inspect an expected exception, you can capture it using this syntax:
This expression returns the caught exception so that you can inspect it further:
you can also capture and inspect an expected exception in one statement, like this: