Verify that method throws IllegalArgumentException for invalid input
Preconditions (2)
✅ Expected Result: The method throws IllegalArgumentException with the correct message when called with negative age
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class DiscountCalculatorTest { @Test void calculateDiscount_throwsException_forNegativeAge() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { DiscountCalculator.calculateDiscount(-5); }); assertTrue(exception.getMessage().contains("Age cannot be negative")); } } class DiscountCalculator { public static double calculateDiscount(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } // Simple discount logic for example return age > 60 ? 0.2 : 0.0; } }
This test uses assertThrows to check that the method calculateDiscount throws an IllegalArgumentException when given a negative age.
We capture the exception and then verify its message contains the expected text. This confirms the error handling works as intended.
Using assertThrows is best practice because it clearly expresses the test's purpose and avoids manual try-catch blocks.
The method calculateDiscount is a simple example that throws the exception for invalid input.
Now add data-driven testing with 3 different invalid age inputs: -1, -10, and -100
NullPointerException?@Test
void testDivide() {
assertThrows(ArithmeticException.class, () -> divide(10, 0));
}
int divide(int a, int b) {
return a / b;
}IllegalArgumentException:@Test
void test() {
assertThrows(IllegalArgumentException.class, method());
}
void method() {
throw new IllegalArgumentException();
}IOException only when a file is missing. Which approach best validates this error handling using JUnit 5 exception testing?Pass the test and this pattern moves unknown