Test Overview
This test checks that a method throws the expected exception when given invalid input. It verifies that the exception type and message are correct.
This test checks that a method throws the expected exception when given invalid input. It verifies that the exception type and message are correct.
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class Calculator { int divide(int a, int b) { if (b == 0) { throw new IllegalArgumentException("Divider cannot be zero"); } return a / b; } } public class CalculatorTest { @Test void testDivideByZeroThrowsException() { Calculator calc = new Calculator(); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { calc.divide(10, 0); }); assertEquals("Divider cannot be zero", exception.getMessage()); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | - | PASS |
| 2 | Calculator object created | Calculator instance ready | - | PASS |
| 3 | assertThrows called with IllegalArgumentException.class and lambda calling divide(10, 0) | Executing divide method with b=0 | Exception of type IllegalArgumentException is thrown | PASS |
| 4 | Exception caught by assertThrows and stored | Exception message: 'Divider cannot be zero' | Exception message equals 'Divider cannot be zero' | PASS |
| 5 | Test ends successfully | Test passed with expected exception | - | PASS |