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

岁酱吖の 提交于 2020-07-28 11:36:49

问题:

How can I use JUnit4 idiomatically to test that some code throws an exception? 如何惯用JUnit4来测试某些代码引发异常?

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);
}

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. 我记得在这种情况下,有一个批注或一个Assert.xyz或一些不那么杂乱无章的东西 ,更是JUnit的精髓。


解决方案:

参考一: https://stackoom.com/question/eiF/您如何断言在JUnit-测试中引发了某种异常
参考二: https://oldbug.net/q/eiF/How-do-you-assert-that-a-certain-exception-is-thrown-in-JUnit-4-tests
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!