你如何断言在 JUnit 4 测试中抛出了某个异常? [英] How do you assert that a certain exception is thrown in JUnit 4 tests?

查看:27
本文介绍了你如何断言在 JUnit 4 测试中抛出了某个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I use JUnit4 idiomatically to test that some code throws an exception?

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

While I can certainly do something like this:

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

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

  assertTrue(thrown);
}

我记得有一个注解或 Assert.xyz 或某些东西对于这些类型的情况远不那么笨拙,而且更符合 JUnit 的精神.

I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.

推荐答案

这取决于 JUnit 版本以及您使用的断言库.

It depends on the JUnit version and what assert libraries you use.

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.

Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.

参考:

这篇关于你如何断言在 JUnit 4 测试中抛出了某个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆