使用“不应该产生[异常]"ScalaTest 中的语法 [英] Using the "should NOT produce [exception]" syntax in ScalaTest

查看:44
本文介绍了使用“不应该产生[异常]"ScalaTest 中的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Scala 中使用 Specs2 和 ScalaTest 来实现 BDD.当我断言不应该抛出给定的异常时,我已经在 Specs2 中写下了期望.

I'am toying with Specs2 and ScalaTest for BDD in Scala. I've written expectations in Specs2 when I am asserting that a given exception should not be thrown.

"do something" in {
 {
   ....
 } must not(throwA[MyException])
}

我希望能够在 ScalaTest 中编写类似的代码:

I was hoping to be able to write the equivalent in ScalaTest like:

"do something" in {
 evaluating {
   ....
 } should not produce[MyException]
}

但这不能编译,我找不到这样做的方法.这可能吗?

But this does not compile and I could not find way of doing it. Is that even possible?

非常感谢.

推荐答案

这在最新版本的 ScalaTest 中是不能直接实现的,因为 EvaluatingApplicationShouldWrapper 的方法 should 没有有一个采用 NotWord 的重载,只有一个采用 ResultOfProduceInvocation[T].

This is not possible directly in the latest version of ScalaTest because the method should of EvaluatingApplicationShouldWrapper does not have an overload that takes a NotWord, only one that takes a ResultOfProduceInvocation[T].

我建议只让不需要的异常发生,这将使测试失败.这是经典的方式.

I'd suggest just letting the undesired exception happen, which will fail the test. This is the classic way.

但是如果您觉得需要更清楚地了解究竟是什么失败了,您可以使用 try-catch 块来处理错误.如果您发现不希望发生的错误,请通过调用 fail 方法处理异常:

But if you feel you need more clarity about what failed exactly, you could use a try-catch block to handle the error. If you catch the error you don't want to happen, handle the exception with a call to the fail method:

fail("That expression shouldn't have thrown a MyExceptionType exception")

这篇关于使用“不应该产生[异常]"ScalaTest 中的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆