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.
I think this is an even simpler example
Calling
get()
on an optional containing an emptyArrayList
will throw aNoSuchElementException
.assertThrows
declares the expected exception and provides a lambda supplier (takes no arguments and returns a value).Thanks to @prime for his answer which I hopefully elaborated on.
Now Junit5 provides a way to assert the exceptions
You can test both general exceptions and customized exceptions
A general exception scenario:
ExpectGeneralException.java
ExpectGeneralExceptionTest.java
You can find a sample to test CustomException here : assert exception code sample
ExpectCustomException.java
ExpectCustomExceptionTest.java
They've changed it in JUnit 5 (expected: InvalidArgumentException, actual: invoked method) and code looks like this one:
Actually I think there is a error in the documentation for this particular example. The method that is intended is expectThrows
In Java 8 and JUnit 5 (Jupiter) we can assert for exceptions as follows. Using
org.junit.jupiter.api.Assertions.assertThrows
That approach will use the Functional Interface
Executable
inorg.junit.jupiter.api
.Refer :
You can use
assertThrows()
. My example is taken from the docs http://junit.org/junit5/docs/current/user-guide/