本文介绍了您如何断言在 JUnit 4 测试中引发了某个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以惯用方式使用 JUnit4 来测试某些代码是否引发异常?
How can I use JUnit4 idiomatically to test that some code throws an exception?
虽然我当然可以这样做:
While I can certainly do something like this:
@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
我记得有一个注解或一个 Assert.xyz 或 something 远不那么笨拙,而且在这类情况下更符合 JUnit 的精神.
I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.
推荐答案
这取决于 JUnit 版本和你使用的断言库.
It depends on the JUnit version and what assert libraries you use.
- 对于 JUnit5 和 4.13,请参阅答案 https://stackoverflow.com/a/2935935/2986984
- 如果您使用 assertJ 或 google-truth,请参阅答案 https://stackoverflow.com/a/41019785/2986984
JUnit <= 4.12
的原始答案是:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
虽然答案 https://stackoverflow.com/a/31826781/2986984 对 JUnit <= 有更多选择4.12.
Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.
参考:
这篇关于您如何断言在 JUnit 4 测试中引发了某个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!