Test Overview
This test checks that the method correctly throws an exception when given invalid input. It verifies that the error handling works as expected by catching the exception.
This test checks that the method correctly throws an exception when given invalid input. It verifies that the error handling works as expected by catching the exception.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CalculatorTest { @Test void testDivideByZeroThrowsException() { Calculator calc = new Calculator(); Exception exception = assertThrows(ArithmeticException.class, () -> { calc.divide(10, 0); }); assertEquals("Division by zero", exception.getMessage()); } } class Calculator { public int divide(int a, int b) { if (b == 0) { throw new ArithmeticException("Division by zero"); } return a / b; } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | - | PASS |
| 2 | Calculator object created | Calculator instance ready | - | PASS |
| 3 | Calls divide(10, 0) | Method executes and throws ArithmeticException | assertThrows verifies ArithmeticException is thrown | PASS |
| 4 | Checks exception message equals 'Division by zero' | Exception caught with message 'Division by zero' | assertEquals verifies exception message | PASS |
| 5 | Test ends | Test passed successfully | - | PASS |