您如何断言在 JUnit 测试中引发了某个异常?

新手上路,请多包涵

如何以惯用方式使用 JUnit 来测试某些代码是否引发异常?

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

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

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

  assertTrue(thrown);
}

我记得有一个注释或一个 Assert.xyz 或 _其他东西_,在这种情况下,JUnit 的精神远不那么笨拙,而且更符合 JUnit 的精神。

原文由 SCdF 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

这取决于 JUnit 版本和您使用的断言库。

JUnit <= 4.12 的原始答案是:

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

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

}

虽然答案 https://stackoverflow.com/a/31826781/2986984 有更多 JUnit <= 4.12 的选项。

参考 :

原文由 skaffman 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

如果您还没有迁移到 JUnit 5,但可以使用 JUnit 4.7,则可以使用 ExpectedException 规则:

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

有关详细信息,请参阅 本文

原文由 NamshubWriter 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题