如何以惯用的方式使用 JUnit 来测试某些代码是否抛出异常?
虽然我当然可以做这样的事情:
@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
我记得有一个注解或 Assert.xyz 或东西对于这类情况来说远没有那么笨拙而且更符合 JUnit 的精神。
最佳答案
这取决于 JUnit 版本和您使用的断言库。
- 对于 JUnit5 和 4.13 see answer
- 如果您使用 AssertJ 或 google-truth,see answer
JUnit <= 4.12
的原始答案是:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
虽然answer为 JUnit <= 4.12 提供了更多选项。
引用:
关于java - 您如何断言在 JUnit 测试中抛出了某个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58881971/