且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何断言在 JUnit 4 测试中抛出了某个异常?

更新时间:2023-11-20 08:36:58

这取决于 JUnit 版本以及您使用的断言库.

It depends on the JUnit version and what assert libraries you use.

JUnit 的原始答案是:

@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {

    ArrayList emptyList = new ArrayList();
    Object o = emptyList.get(0);

}

虽然回答 https://***.com/a/31826781/2986984 有更多 JUnit 选项 <=4.12.

Though answer https://***.com/a/31826781/2986984 has more options for JUnit <= 4.12.

参考: