Scala的Specs BDD库中的异常匹配器

11

我正在使用Specs BDD库来编写Scala单元测试(http://code.google.com/p/specs)。 如果我想要断言一个抛出了ClassNotFoundException类型的异常,那么我可以编写以下代码:

a must throwA[ClassNotFoundException]

然而,我想测试反向情况,即我想要断言一个“不会”抛出类型为 ClassNotFoundException 的异常。

我尝试使用否定匹配器,如下所示:

 a must throwA[ClassNotFoundException].not

但那不起作用。我收到编译错误。那么,有没有办法断言例如ClassNotFoundException类型的异常不会被抛出?

请帮忙 谢谢

4个回答

17

编译时存在解析问题。

 a must throwA[ClassNotFoundException].not

你需要改为以下写法:

 a must not(throwA[ClassNotFoundException])

2
像这样的东西怎么样:
"An isSpaceNode function" should {
    "not fail with a Group" in {
       Group(<a/><b/>).isSpaceNode must not throwA(new UnsupportedOperationException)
    }
}

2
以下测试在表达式抛出除了 ClassNotFoundException 以外的任何内容时都会通过:
 must throwA[Exception].like {
    case m:  ClassNotFoundException => false
    case _ => true}

如果您只是想确保该表达式不会抛出ClassNotFoundException异常,为什么不使用try-catch块:

try{
         ...
    }catch{
        case m:  ClassNotFoundException => fail("ClassNotFoundException")
        case e => e.printStackTrace
}

2

即使它没有解决你的问题,你也不必测试是否会抛出异常。在这种情况下,最好检查预期结果是否正确...一旦测试执行,就意味着它不会抛出异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接