Assertions: assertThrows() and assertThrowsExactly()

Let's learn assertThrows() and assertThrowsExactly() assertions in JUnit 5.

The assertThrows() method

The assertThrows() method asserts that the execution of the given Executable throws an exception of the expectedType. The thrown exception is returned for further assertions.

  • If the expectedType is Exception and the actual is RuntimeException, the assertion passes.
  • If no exception is thrown, or if an exception of a different type is thrown, the method fails.

Get hands-on with 1200+ tech skills courses.