小编典典

您如何断言在JUnit 4测试中抛出了某个异常?

java

如何惯用JUnit4来测试某些代码引发异常?

虽然我当然可以做这样的事情:

@Test
public void testFooThrowsIndexOutOfBoundsException() {
  boolean thrown = false;

  try {
    foo.doStuff();
  } catch (IndexOutOfBoundsException e) {
    thrown = true;
  }

  assertTrue(thrown);
}

我记得在这种情况下,有一个批注或一个Assert.xyz或一些不太灵活的JUnit东西。


阅读 911

收藏
2020-02-26

共2个答案

小编典典

JUnit 4 有对此的支持:

@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {

    ArrayList emptyList = new ArrayList();
    Object o = emptyList.get(0);

}
2020-02-26
小编典典

现在已经发布了JUnit 5和JUnit 4.13,最好的选择是使用Assertions.assertThrows() (对于JUnit 5)和Assert.assertThrows()(对于JUnit 4.13)。请参阅我的其他答案以获取详细信息。

如果尚未迁移到JUnit 5,但可以使用JUnit 4.7,则可以使用ExpectedExceptionRule:

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)因为如果IndexOutOfBoundsException之前抛出测试,测试将失败foo.doStuff()

2020-02-26