0
0
JUnittesting~5 mins

Testing multiple exceptions in JUnit

Choose your learning style9 modes available
Introduction

We test multiple exceptions to check that our code handles different error cases correctly. This helps catch bugs and makes the program more reliable.

When a method can throw different exceptions for different problems.
When you want to verify that your code throws the right exception for each error.
When you want to make sure your error handling works for all expected failure cases.
Syntax
JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;

@Test
void testMultipleExceptions() {
    assertThrows(ExceptionType1.class, () -> methodThatThrowsException1());
    assertThrows(ExceptionType2.class, () -> methodThatThrowsException2());
}

Use assertThrows for each exception you want to test.

Each assertThrows checks one specific exception type.

Examples
Tests that someMethod throws NullPointerException when given null.
JUnit
assertThrows(NullPointerException.class, () -> someMethod(null));
Tests that someMethod throws IllegalArgumentException when given a negative number.
JUnit
assertThrows(IllegalArgumentException.class, () -> someMethod(-1));
Sample Program

This test checks that the divide method throws ArithmeticException when dividing by zero, and IllegalArgumentException when either number is negative.

JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;

class Calculator {
    int divide(int a, int b) {
        if (b == 0) throw new ArithmeticException("Divide by zero");
        if (a < 0 || b < 0) throw new IllegalArgumentException("Negative number");
        return a / b;
    }
}

public class CalculatorTest {
    Calculator calc = new Calculator();

    @Test
    void testDivideExceptions() {
        assertThrows(ArithmeticException.class, () -> calc.divide(10, 0));
        assertThrows(IllegalArgumentException.class, () -> calc.divide(-5, 2));
        assertThrows(IllegalArgumentException.class, () -> calc.divide(5, -2));
    }
}
OutputSuccess
Important Notes

Each assertThrows should test one exception case clearly.

Keep tests small and focused for easier debugging.

Summary

Use assertThrows to test each expected exception separately.

Testing multiple exceptions helps ensure your code handles errors well.