Verify that dividing by zero throws ArithmeticException
Preconditions (2)
✅ 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
assertThrows in JUnit testing?assertThrowsassertThrows is designed to check if a certain exception occurs when running some code.assertThrows in JUnit 5?assertThrows(Exception.class, executable) where executable is a lambda or method reference.import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void testDivideByZero() {
assertThrows(ArithmeticException.class, () -> {
int result = 10 / 0;
});
}assertThrows:@Test
void testNullPointer() {
assertThrows(NullPointerException, () -> {
String s = null;
s.length();
});
}NullPointerException.class, not just the class name.parseNumber(String s) throws NumberFormatException only when the input is not a valid number. Which of these tests correctly uses assertThrows to check this behavior?Pass the test and this pattern moves unknown