'How can I test if a particular exception is not thrown?
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?
Solution 1:[1]
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");
Solution 2:[2]
catch-exception makes the example of Freiheit a bit more concise:
catchException(a).myMethod();
assertFalse(caughtException() instanceof ExceptionNotToThrow);
Solution 3:[3]
Another latest solution could be using Junit5 assertDoesNotThrow:
assertDoesNotThrow( () -> myMethod() , "MyException is not thrown")
Solution 4:[4]
Use @Test(expected = Test.None::class) (in Kotlin)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Djalas |
| Solution 2 | rwitzel |
| Solution 3 | Sasi Kathimanda |
| Solution 4 | jhavatar |
