【问题标题】:How can I test if a particular exception is not thrown?如何测试是否未引发特定异常?
【发布时间】:2022-04-27 05:23:06
【问题描述】:

我能否测试是否抛出特定异常?

反之,使用@Test[expect=MyException] 很容易。

但是我怎样才能否定这一点呢?

【问题讨论】:

  • 这将测试是否抛出异常。如果没有抛出异常,它将失败。所以它已经做了你想要的(?)
  • 您的标题(在编辑之前和之后)与您的问题文本相矛盾。你具体想做什么?
  • 抱歉,我该如何测试是否没有抛出特定异常

标签: junit


【解决方案1】:

如果您想测试在可能抛出其他异常的情况下是否抛出特定异常,试试这个:

try {
  myMethod();
}
catch (ExceptionNotToThrow entt){
  fail("WHOOPS! Threw ExceptionNotToThrow" + entt.toString);
}
catch (Throwable t){
  //do nothing since other exceptions are OK
}
assertTrue(somethingElse);
//done!

【讨论】:

    【解决方案2】:

    您可以使用assertj 执行以下操作

    如果你想检查是否没有抛出异常

    Throwable throwable = catchThrowable(() -> sut.method());
    
    assertThat(throwable).isNull();
    

    或者你希望抛出

    Throwable throwable = catchThrowable(() -> sut.method());
    
    assertThat(throwable).isInstanceOf(ClassOfExecption.class)
                         .hasMessageContaining("expected message");
    

    【讨论】:

      【解决方案3】:

      catch-exception 让 Freiheit 的例子更加简洁:

      catchException(a).myMethod();
      assertFalse(caughtException() instanceof ExceptionNotToThrow);
      

      【讨论】:

        【解决方案4】:

        另一个最新的解决方案可能是使用 Junit5 assertDoesNotThrow

        assertDoesNotThrow( () -> myMethod() , "MyException is not thrown")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-28
          • 2018-01-16
          • 2010-09-12
          • 1970-01-01
          • 1970-01-01
          • 2020-01-13
          相关资源
          最近更新 更多