Test Overview
This test verifies that a method throws the correct exception type and that the exception is a subclass of the expected exception hierarchy.
This test verifies that a method throws the correct exception type and that the exception is a subclass of the expected exception hierarchy.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class ExceptionHierarchyTest { void methodThatThrows() throws IllegalArgumentException { throw new IllegalArgumentException("Invalid argument"); } @Test void testExceptionTypeHierarchy() { Exception exception = assertThrows(Exception.class, () -> methodThatThrows()); assertTrue(exception instanceof IllegalArgumentException, "Exception should be IllegalArgumentException"); assertTrue(exception instanceof RuntimeException, "Exception should be a RuntimeException subclass"); assertTrue(exception instanceof Exception, "Exception should be an Exception subclass"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | - | PASS |
| 2 | Calls methodThatThrows() inside assertThrows expecting Exception.class | methodThatThrows() throws IllegalArgumentException | assertThrows captures the thrown IllegalArgumentException as Exception | PASS |
| 3 | Checks if caught exception is instance of IllegalArgumentException | exception is IllegalArgumentException | assertTrue passes because exception is IllegalArgumentException | PASS |
| 4 | Checks if caught exception is instance of RuntimeException | IllegalArgumentException extends RuntimeException | assertTrue passes because exception is subclass of RuntimeException | PASS |
| 5 | Checks if caught exception is instance of Exception | RuntimeException extends Exception | assertTrue passes because exception is subclass of Exception | PASS |
| 6 | Test ends successfully | All assertions passed | - | PASS |