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

标签 java exception junit junit4 assert

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

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

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

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

  assertTrue(thrown);
}

我记得有一个注解或 Assert.xyz 或东西对于这类情况来说远没有那么笨拙而且更符合 JUnit 的精神。

最佳答案

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

JUnit <= 4.12 的原始答案是:

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

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

    }

虽然answer为 JUnit <= 4.12 提供了更多选项。

引用:

关于java - 您如何断言在 JUnit 测试中抛出了某个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58881971/

相关文章:

java - 将字符串转换为枚举而不发出警告

java - 在此工作簿中检测到一个或多个无效名称。这些无效名称已更改为#REF

java - 无法捕获 junit 中的算术异常

java - 为什么struts2-junit插件提示约定插件?

javascript - 如何让客户端知道 servlet 处理请求时发生了什么?

java - If 语句与 String.equals()

c# - 在 catch block 中返回?

javascript - 如何禁用 Visual Studio 未处理的异常

java - 我在哪里可以在 Spring 捕获非休息 Controller 异常?

java - 如何从终端使用junit