@Test(expected=IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); }
这种方式比@Test(expected=IndexOutOfBoundsException.class)要更好,如果是在调用foo.doStuff()方法之前就已经抛出异常的话,测试结果就不是我们想要的了。 (译者:同时,ExpectedException还能够验证异常信息,如exception.expectMessage("there is an exception!");