本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看活动链接
提问:你是怎么断言在 JUnit 4 测试中抛出某个异常的?
如何使用 JUnit 4 来测试某些代码引发异常?
我可以像这样做:
@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
我记得有一个注解或者 assert.xyz 或者其他的东西,在这种情况下,它远没有那么笨拙,更符合 junit 的思想。
高分回答1:
更新回答:
这取决于你所使用的 JUnit 版本和 assert 库。
- 如果你使用的是
JUnit 5和 4.13 的库版本,可以参考这个回答:stackoverflow.com/a/2935935/2… - 如果你用的是
assertJ或者google-truth,可以参考这个回答:stackoverflow.com/a/41019785/…
原始回答:
如果你的版本 JUnit <= 4.12 ,那么 Junit 4 对此提供了支持:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
高分回答2:
既然 JUnit 5 已经发布了,最好的选择是使用 Assertions.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) 好得多,因为如果在 foo.doStuff() 之前抛出 IndexOutOfBoundsException 测试将会失败。
有关详细信息,请参阅本文。
高分回答3:
小心使用预期的异常,因为它只声明方法抛出了该异常,而不是测试中的特定代码行。
我倾向于将其用于测试参数验证,因为此类方法通常非常简单,但更复杂的测试可能更好地用于:
try {
methodThatShouldThrow();
fail("My method didn't throw when I expected it to" );
} catch (MyException expectedException) {
}
运用判断。
出处
文章翻译自 Stack Overflow :How do you assert that a certain exception is thrown in JUnit 4 tests?