如何在junit中判斷指定異常的拋出

 

 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 testFooThrowsIndexOutOfBoundsException() {
 boolean thrown = false;
 
 try {
  foo.doStuff();
 } catch (IndexOutOfBoundsException e) {
  thrown = true;
 }
 
  assertTrue(thrown);
}
 
JUnit 4 has support for this:
 @Test(expected=IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
 ArrayList emptyList = new ArrayList();
 Object o = emptyList.get(0);
}

If you can use JUnit 4.7, you can use the ExpectedException Rule
 @RunWith(JUnit4.class)
public class FooTest {
 @Rule
 public ExpectedException exception = ExpectedException.none();
 
 @Test
 public void doStuffThrowsIndexOutOfBoundsException() {
 Foo foo = new Foo();
 
  exception.expect(IndexOutOfBoundsException.class);
  foo.doStuff();
 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章