0
0
JUnittesting~10 mins

assertThrows usage 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 assertThrows correctly catches the exception type.

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

class Calculator {
    int divide(int a, int b) {
        return a / b;
    }
}

public class CalculatorTest {
    @Test
    void testDivideByZeroThrows() {
        Calculator calc = new Calculator();
        assertThrows(ArithmeticException.class, () -> calc.divide(10, 0));
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2CalculatorTest.testDivideByZeroThrows method invokedCalculator instance created-PASS
3assertThrows called with ArithmeticException.class and lambda dividing 10 by 0Lambda executed, division by zero attemptedCheck if ArithmeticException is thrownPASS
4ArithmeticException thrown by divide methodException caught by assertThrowsException type matches expected ArithmeticExceptionPASS
5Test completes successfullyTest runner reports test passedassertThrows assertion passedPASS
Failure Scenario
Failing Condition: divide method does not throw ArithmeticException when dividing by zero
Execution Trace Quiz - 3 Questions
Test your understanding
What does assertThrows verify in this test?
AThat the divide method throws ArithmeticException when dividing by zero
BThat the divide method returns zero when dividing by zero
CThat no exception is thrown during division
DThat the divide method throws NullPointerException
Key Result
Use assertThrows to clearly and safely verify that a specific exception is thrown by a code block, improving test clarity and correctness.