Using the “should NOT produce [exception]” syntax in ScalaTest

穿精又带淫゛_ 提交于 2019-12-09 14:03:48

问题


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])
}

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?

Many thanks in advance.


回答1:


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.

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



回答2:


The current version of ScalaTest does support this:

noException should be thrownBy 0 / 1

See docs.



来源:https://stackoverflow.com/questions/6994886/using-the-should-not-produce-exception-syntax-in-scalatest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!