Introduction
In this article, we look at how to verify exceptions with JUnit5. We will cover how to verify an exception, verify a specific exception thrown, No exception is thrown, and assert that list of Executable's don't throw an exception.
Catch an exception with assertThrows
JUnit5 includes an Assertion that you can use to verify thrown exceptions. The method takes two parameters: the type of exception you expect and an Executable. The executable can be a Lambda expression, method reference, or implementation of the Executable interface.
In the following example, we catch the exception the Car class throws and verify the message inside the exception is what we expected it to be.
|
|
The test won't fail if a subtype of the exception is thrown.
Catch a specific exception with assertThrowsExactly
If you want to verify that a specific exception is thrown, you will have to use assertThrowsExactly
. In the following
example, we call a method that throws an EOFException. If the method throws any other exception, the test will fail.
|
|
Verifying a specific exception is not thrown with assertDoesNotThrow
Yes, any execution thrown from a test method would cause a test to fail. There are cases where it can be handy to explicitly verify an exception is not thrown.
|
|
Using assertAll to verify multiple Executables
JUnit also offers an Assertion to verify that multiple Executables don't throw an exception.
In the following example, we pass a list of Executables to the assertAll method that will verify that none of the lambda's will throw an exception.
|
|
Conclusion
This article looked at different ways to catch exceptions and verify their content. We also looked at two cases that verify no exception is thrown.
Further reading
More about testing in Java: