猿问

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

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

如何使用JUnit 4来习惯地测试某些代码抛出异常?

我当然可以这样做:

@Testpublic void testFooThrowsIndexOutOfBoundsException() {
  boolean thrown = false;

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

  assertTrue(thrown);}

我记得有注释或Assert.xyz或某物对于这类情况,这要少得多,更多的是JUnit的精神。


烙印99
浏览 3557回答 3
3回答

胡子哥哥

编辑既然JUnit 5已经发布,最好的选择就是使用Assertions.assertThrows()(见我的另一个答案).如果尚未迁移到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)因为如果IndexOutOfBoundsException在此之前抛出foo.doStuff()看见这篇文章详情

米琪卡哇伊

小心使用预期异常,因为它只断言方法抛出那个例外,而不是一个特定代码行在测试中。我倾向于将其用于测试参数验证,因为此类方法通常非常简单,但更复杂的测试最好使用:try {     methodThatShouldThrow();     fail( "My method didn't throw when I expected it to" );} catch (MyException expectedException) {}作出判断。
随时随地看视频慕课网APP

相关分类

Java
我要回答