Test Overview
This test verifies that a method throws an IllegalArgumentException with the expected message when given invalid input.
This test verifies that a method throws an IllegalArgumentException with the expected message when given invalid input.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CalculatorTest { @Test void testDivideByZeroThrowsExceptionWithMessage() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { Calculator.divide(10, 0); }); assertEquals("Cannot divide by zero", exception.getMessage()); } } class Calculator { public static int divide(int a, int b) { if (b == 0) { throw new IllegalArgumentException("Cannot divide by zero"); } return a / b; } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | - | PASS |
| 2 | Calls Calculator.divide(10, 0) | Method invoked with divisor zero | - | PASS |
| 3 | Calculator.divide throws IllegalArgumentException with message 'Cannot divide by zero' | Exception thrown and caught by assertThrows | Exception type is IllegalArgumentException | PASS |
| 4 | Assert exception message equals 'Cannot divide by zero' | Exception message retrieved | assertEquals("Cannot divide by zero", exception.getMessage()) | PASS |
| 5 | Test ends successfully | Test passed with expected exception and message | - | PASS |