0
0
JUnittesting~10 mins

Why exception testing validates error handling in JUnit - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test checks that the method correctly throws an exception when given invalid input. It verifies that the error handling works as expected by catching the exception.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {

    @Test
    void testDivideByZeroThrowsException() {
        Calculator calc = new Calculator();
        Exception exception = assertThrows(ArithmeticException.class, () -> {
            calc.divide(10, 0);
        });
        assertEquals("Division by zero", exception.getMessage());
    }
}

class Calculator {
    public int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Division by zero");
        }
        return a / b;
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Calculator object createdCalculator instance ready-PASS
3Calls divide(10, 0)Method executes and throws ArithmeticExceptionassertThrows verifies ArithmeticException is thrownPASS
4Checks exception message equals 'Division by zero'Exception caught with message 'Division by zero'assertEquals verifies exception messagePASS
5Test endsTest passed successfully-PASS
Failure Scenario
Failing Condition: Method does not throw ArithmeticException when dividing by zero
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify about the divide method?
AIt throws ArithmeticException when dividing by zero
BIt returns zero when dividing by zero
CIt throws NullPointerException when dividing by zero
DIt returns the correct division result
Key Result
Exception testing ensures that error handling code runs correctly by verifying that the expected exceptions are thrown for invalid inputs.