如何测试是否未抛出特定异常?

Acd*_*oll 16 junit

我可以测试是否没有抛出特定的异常吗?

反过来很容易使用@Test[expect=MyException].

但我怎么能否定这个呢?

Fre*_*eit 17

如果你想测试一个特定的例外是不是在一个条件下抛出其他异常可能会被抛出,试试这个:

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


Dja*_*las 6

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

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

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

assertThat(throwable).isNull();
Run Code Online (Sandbox Code Playgroud)

或者你希望抛出

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

assertThat(throwable).isInstanceOf(ClassOfExecption.class)
                     .hasMessageContaining("expected message");
Run Code Online (Sandbox Code Playgroud)