0
0
JUnittesting~10 mins

assertThrows for exceptions in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a method throws the expected exception when given invalid input. It verifies that the exception type and message are correct.

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

class Calculator {
    int divide(int a, int b) {
        if (b == 0) {
            throw new IllegalArgumentException("Divider cannot be zero");
        }
        return a / b;
    }
}

public class CalculatorTest {
    @Test
    void testDivideByZeroThrowsException() {
        Calculator calc = new Calculator();
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
            calc.divide(10, 0);
        });
        assertEquals("Divider cannot be zero", exception.getMessage());
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Calculator object createdCalculator instance ready-PASS
3assertThrows called with IllegalArgumentException.class and lambda calling divide(10, 0)Executing divide method with b=0Exception of type IllegalArgumentException is thrownPASS
4Exception caught by assertThrows and storedException message: 'Divider cannot be zero'Exception message equals 'Divider cannot be zero'PASS
5Test ends successfullyTest passed with expected exception-PASS
Failure Scenario
Failing Condition: divide method does not throw IllegalArgumentException when dividing by zero
Execution Trace Quiz - 3 Questions
Test your understanding
What does assertThrows verify in this test?
AThat the divide method does not throw any exception
BThat the divide method returns zero when dividing by zero
CThat the divide method throws IllegalArgumentException when dividing by zero
DThat the divide method throws NullPointerException
Key Result
Use assertThrows to verify that your code throws the correct exception type and then check the exception message to ensure the error is exactly what you expect.