`

junit使用

 
阅读更多
参考:单元测试利器 JUnit 4
http://www.ibm.com/developerworks/cn/java/j-lo-junit4/

如何在junit中判断指定异常的抛出
@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();
  }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics