scala 在 ScalaTest 中使用“不应该产生 [异常]”语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6994886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:19:58  来源:igfitidea点击:

Using the "should NOT produce [exception]" syntax in ScalaTest

scalaspecsscalatest

提问by Guillaume Belrose

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.

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

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

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

我希望能够在 ScalaTest 中编写等效的代码,例如:

"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?

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

Many thanks in advance.

提前谢谢了。

采纳答案by traffichazard

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

这直接是不可能的ScalaTest的最新版本,因为该方法shouldEvaluatingApplicationShouldWrapper不具有过载,需要一个NotWord,只有一个需要ResultOfProduceInvocation[T]

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

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

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

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

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

回答by Wolfram Arnold

The current version of ScalaTest does support this:

当前版本的 ScalaTest 确实支持:

noException should be thrownBy 0 / 1

See docs.

请参阅文档