JUnit4如何断言确定异常的抛出 |
您所在的位置:网站首页 › 长春南关区邮编码 › JUnit4如何断言确定异常的抛出 |
Java 必知必会 第 35 篇 how do you assert that a certain exception is thrown in junit-4 tests 问题在JUnit4单元测试中,我要怎样做才能测试出有特定的异常抛出?我能想到的就只有下面的方法: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } 回答1在JUnit4后支持下面的写法: @Test(expected=IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); }(译者:在@Test注解内提供了expected属性,你可以用它来指定一个Throwble类型,如果方法调用中抛出了这个异常,那么这条测试用例就相当于通过了) 回答2如果你使用的是JUnit4.7,你可以使用如下的期望异常规则来验证异常信息: 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()方法之前就已经抛出异常的话,测试结果就不是我们想要的了。 (译者:同时,ExpectedException还能够验证异常信息,如exception.expectMessage("there is an exception!"); 拓展阅读 JUnit:使用ExpectedException进行异常测试JUnit4 用法详解 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |