Test Overview
This test checks that a method throws the expected exception when given invalid input. It verifies that assertThrows correctly catches the exception type.
This test checks that a method throws the expected exception when given invalid input. It verifies that assertThrows correctly catches the exception type.
import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; class Calculator { int divide(int a, int b) { return a / b; } } public class CalculatorTest { @Test void testDivideByZeroThrows() { Calculator calc = new Calculator(); assertThrows(ArithmeticException.class, () -> calc.divide(10, 0)); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | - | PASS |
| 2 | CalculatorTest.testDivideByZeroThrows method invoked | Calculator instance created | - | PASS |
| 3 | assertThrows called with ArithmeticException.class and lambda dividing 10 by 0 | Lambda executed, division by zero attempted | Check if ArithmeticException is thrown | PASS |
| 4 | ArithmeticException thrown by divide method | Exception caught by assertThrows | Exception type matches expected ArithmeticException | PASS |
| 5 | Test completes successfully | Test runner reports test passed | assertThrows assertion passed | PASS |