JUnit assertThrows Example

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

  1. Eclipse photon (only this eclipse version supports JUnit 5)
  2. Maven
  3. JUnit 5
  4. JDK 8 or later

assertThrows Methods

There three overloaded versions of assertThrows static methods.
  1. static T assertThrows(Class expectedType, Executable executable) - Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
  2. 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.
  3. 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

Comments