Verify that dividing by zero throws ArithmeticException
Preconditions (2)
Step 1: Call divide(10, 0)
Step 2: Check that ArithmeticException is thrown
✅ Expected Result: The test passes only if ArithmeticException is thrown when dividing by zero
import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class CalculatorTest { public int divide(int a, int b) { return a / b; } @Test void testDivideByZeroThrows() { assertThrows(ArithmeticException.class, () -> divide(10, 0)); } }
The test class CalculatorTest contains a simple divide method that divides two integers.
The test method testDivideByZeroThrows uses assertThrows from JUnit 5 to check that calling divide(10, 0) throws an ArithmeticException.
The lambda () -> divide(10, 0) is passed to assertThrows so JUnit can run it and catch the exception.
This approach is clean and avoids try-catch blocks in the test, making the test easy to read and maintain.
Now add data-driven testing with 3 different inputs that throw ArithmeticException