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 |
assertThrows in JUnit testing?assertThrows is used to test if a particular exception occurs when running a piece of code.assertThrows specifically checks for exceptions.assertThrows in JUnit 5?assertThrows(Exception.class, Executable) where Executable is a lambda or method reference.assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("Invalid argument");
});IllegalArgumentException, which matches the expected exception class.assertThrows(NullPointerException.class, () -> {
String s = null;
s.length();
});s.length() on a null string throws NullPointerException.NullPointerException.class, matching the thrown exception.void testDivideByZero() {
ArithmeticException thrown = assertThrows(ArithmeticException.class, () -> {
int result = 10 / 0;
});
assertEquals("/ by zero", thrown.getMessage());
}thrown.Pass the test and this pattern moves unknown