jUnit4.5 idiomatically to test that come code throws an exception?
While I can certainly do something like this:
http://blog.sina.com.cn/s/blog_62d0d67b0100twq2.html
@Test
public void testFooThrowsIndexOutOfB oundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsExceptio n e) {
thrown = true;
}
assertTrue(thrown);
}
JUnit 4 has support for this:
@Test(expected=IndexOutOfBoundsExceptio
n.class) public void testIndexOutOfBoundsExce ption() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); }
If you can use JUnit 4.7, you can use theExpectedException
Rule@RunWith(JUnit4.class) public class FooTest {
@Rule public ExpectedException exception = ExpectedException.none(); @Test public void doStuffThrowsIndexOutOfB oundsException() { Foo foo = new Foo(); exception.expect(IndexOutOfBoundsExceptio n.class); foo.doStuff(); } }