How can I test if a particular exception is not th

2019-04-04 06:56发布

问题:

Can I test whether a particular Exception is not thrown?

The other way round is easy using @Test[expect=MyException].

But how can I negate this?

回答1:

If you want to test if a particular Exception is not thrown in a condition where other exceptions could be thrown, try this:

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:

catch-exception makes the example of Freiheit a bit more concise:

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


回答3:

You can do the following using assertj

if you want to check if exception is not thrown then

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

assertThat(throwable).isNull();

or you expect to throw

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

assertThat(throwable).isInstanceOf(ClassOfExecption.class)
                     .hasMessageContaining("expected message");


标签: junit