发布日期:2018-03-26
你如何断言在JUnit在单元测试中抛出了某个异常?+ 查看更多
你如何断言在JUnit在单元测试中抛出了某个异常?
+ 查看更多
发布日期:2018-03-10 14:07
分类:JAVA
浏览次数:564
我该如何使用JUnit惯用的测试方法来测试那些抛出异常的代码?虽然我可以做这样的事情:
@Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); }
我记得有一个注释或者一个断言的方法或者在单元测试中远没有那么复杂并且深入精髓的东西来解释相关的情况。
回答
JUnit 4支持这一点:@Test(expected=IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); }