24

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?

oers
  • 18,436
  • 13
  • 66
  • 75
Acdc RocknRoll
  • 677
  • 5
  • 9
  • 16
  • This will test, that the exception is thrown. It will fail if the exception is not thrown. So it already does what you want (?) – oers Dec 20 '11 at 12:52
  • 1
    Your title (both before and after editing) contradict your question's text. What specifically are you trying to do? – Dave Newton Dec 20 '11 at 12:56
  • Sorry, i ment how can i test if a particular Exception is not thrown – Acdc RocknRoll Dec 20 '11 at 14:30
  • possible duplicate of [How to test that no exception is thrown?](http://stackoverflow.com/questions/17731234/how-to-test-that-no-exception-is-thrown) – Jeroen Vannevel Mar 05 '15 at 15:55

5 Answers5

22

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!
Freiheit
  • 8,408
  • 6
  • 59
  • 101
6

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");
Djalas
  • 1,031
  • 9
  • 6
3

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

catchException(a).myMethod();
assertFalse(caughtException() instanceof ExceptionNotToThrow);
rwitzel
  • 1,694
  • 17
  • 21
1

Another latest solution could be using Junit5 assertDoesNotThrow:

assertDoesNotThrow( () -> myMethod() , "MyException is not thrown")
Sasi Kathimanda
  • 1,788
  • 3
  • 25
  • 47
0

Use @Test(expected = Test.None::class) (in Kotlin)

jhavatar
  • 3,236
  • 1
  • 18
  • 11