.jpg)
如何习惯性地使用 JUnit 来测试某些代码是否引发异常?
虽然我当然可以做这样的事情:
@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
我记得对于这类情况,有一个注释或 Assert.xyz 或其他东西远没有那么笨拙,更符合 JUnit 的精神。

网友回答:
编辑:现在 JUnit 5 和 JUnit 4.13 已经发布,最好的选择是使用 (对于 JUnit 5) 和 (对于 JUnit 4.13+)。有关详细信息,请参阅我的另一个答案。Assertions.assertThrows()Assert.assertThrows()
如果您尚未迁移到 JUnit 5,但可以使用 JUnit 4.7,则可以使用以下规则:ExpectedException
public class FooTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void doStuffThrowsIndexOutOfBoundsException() {
Foo foo = new Foo();
exception.expect(IndexOutOfBoundsException.class);
foo.doStuff();
}
}
这比因为测试在之前抛出会失败要好得多@Test(expected=IndexOutOfBoundsException.class)IndexOutOfBoundsExceptionfoo.doStuff()
有关详细信息,请参阅此文章。

网友回答:
这取决于 JUnit 版本以及您使用的断言库。
最初的答案是:JUnit <= 4.12
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
尽管答案对 JUnit <= 4.12 有更多选择。
参考:

网友回答:
小心使用预期的异常,因为它只断言该方法引发了该异常,而不是测试中的特定代码行。
我倾向于使用它来测试参数验证,因为这样的方法通常非常简单,但更复杂的测试可能最好:
try {
methodThatShouldThrow();
fail( "My method didn't throw when I expected it to" );
} catch (MyException expectedException) {
}
应用判断。
模板简介:该模板名称为【如何习惯性地使用 JUnit 来测试某些代码是否引发异常?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。