Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit 5: How to assert an exception is thrown?

Is there a better way to assert that a method throws an exception in JUnit 5?

Currently, I have to use an @Rule in order to verify that my test throws an exception, but this doesn't work for the cases where I expect multiple methods to throw exceptions in my test.

like image 359
steventrouble Avatar asked Oct 26 '16 17:10

steventrouble


People also ask

How do you assert an exception is thrown JUnit?

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 assert that a certain exception is thrown in JUnit 5 tests?

In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.

How do you assert exception not thrown?

If you want to test a scenario in which an exception should be thrown then you should use the expected annotation. If you want to test a scenario where your code fails and you want to see if the error is correctly handled: use expected and perhaps use asserts to determine if it's been resolved.

How do you test a method that throws an exception?

In order to test the exception thrown by any method in JUnit 4, you need to use @Test(expected=IllegalArgumentException. class) annotation. You can replace IllegalArgumentException. class with any other exception e.g. NullPointerException.


1 Answers

You can use assertThrows(), which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is the canonical way to test for exceptions in JUnit.

Per the JUnit docs:

import static org.junit.jupiter.api.Assertions.assertThrows;  @Test void exceptionTesting() {     MyException thrown = assertThrows(            MyException.class,            () -> myObject.doThing(),            "Expected doThing() to throw, but it didn't"     );      assertTrue(thrown.getMessage().contains("Stuff")); } 
like image 97
12 revs, 8 users 60% Avatar answered Sep 21 '22 09:09

12 revs, 8 users 60%