In this article, we will learn how to do exception testing using assertThrows() static method in JUnit 5. assertThrows() method belongs to JUnit 5 org.junit.jupiter.api.Assertions Class.
Let me list out tools and technologies that I have used to develop JUnit 5 assertThrows Example.
Tools and Technologies Used
- Eclipse photon (only this eclipse version supports JUnit 5)
- Maven
- JUnit 5
- JDK 8 or later
assertThrows Methods
There three overloaded versions of assertThrows static methods.
- static T assertThrows(Class expectedType, Executable executable) - Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
- static T assertThrows (Class expectedType, Executable executable, String message) - Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
- static T assertThrows (Class expectedType, Executable executable, Supplier messageSupplier) - Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
assertThrows Method Example
In this example, we will use above assertThrows methods to demonstrates how to throw an exception in JUnit 5.
assertThrows method asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class AssertThrowsExample {
@Test
void exceptionTesting() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("a message");
});
assertEquals("a message", exception.getMessage());
}
}
Note that we are creating and throwing IllegalArgumentException exception with a message and we check equality of that message using assertEquals() static method.
Output
Reference
https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Assertions.html
Comments
Post a Comment
Leave Comment