Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if a particular exception is not thrown?

Tags:

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?

like image 742
Acdc RocknRoll Avatar asked Dec 20 '11 12:12

Acdc RocknRoll


People also ask

How do I test exceptions in JUnit 4?

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.

How do you test an exception in unit testing?

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.

What is exception testing?

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.


2 Answers

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! 
like image 199
Freiheit Avatar answered Oct 13 '22 05:10

Freiheit


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"); 
like image 29
Djalas Avatar answered Oct 13 '22 05:10

Djalas