如何以惯用方式使用 JUnit 来测试某些代码是否引发异常?
虽然我当然可以做这样的事情:
@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
我记得有一个注释或一个 Assert.xyz 或 _其他东西_,在这种情况下,JUnit 的精神远不那么笨拙,而且更符合 JUnit 的精神。
原文由 SCdF 发布,翻译遵循 CC BY-SA 4.0 许可协议
这取决于 JUnit 版本和您使用的断言库。
JUnit <= 4.12
的原始答案是:虽然答案 https://stackoverflow.com/a/31826781/2986984 有更多 JUnit <= 4.12 的选项。
参考 :