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?
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
assertRaises(exception, callable, *args, **kwds) The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised.
Exception testing is a special feature introduced in JUnit4. In this tutorial, you have learned how to test exception in JUnit using @test(excepted) Junit provides the facility to trace the exception and also to check whether the code is throwing exception or not.
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!
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With