0
0
JUnittesting~10 mins

Checking exception type hierarchy in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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");
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Calls methodThatThrows() inside assertThrows expecting Exception.classmethodThatThrows() throws IllegalArgumentExceptionassertThrows captures the thrown IllegalArgumentException as ExceptionPASS
3Checks if caught exception is instance of IllegalArgumentExceptionexception is IllegalArgumentExceptionassertTrue passes because exception is IllegalArgumentExceptionPASS
4Checks if caught exception is instance of RuntimeExceptionIllegalArgumentException extends RuntimeExceptionassertTrue passes because exception is subclass of RuntimeExceptionPASS
5Checks if caught exception is instance of ExceptionRuntimeException extends ExceptionassertTrue passes because exception is subclass of ExceptionPASS
6Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: methodThatThrows() throws a different exception type or no exception
Execution Trace Quiz - 3 Questions
Test your understanding
Which assertion confirms the exception is exactly IllegalArgumentException or its subclass?
AassertTrue(exception instanceof IllegalArgumentException)
BassertThrows(Exception.class, ...)
CassertTrue(exception instanceof RuntimeException)
DassertTrue(exception instanceof Exception)
Key Result
Use assertThrows with a broad exception type to catch any subclass, then verify the exact exception type with instanceof checks to confirm the exception hierarchy.