0
0
JUnittesting~10 mins

Checking exception message in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test verifies that a method throws an IllegalArgumentException with the expected message when given invalid input.

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

public class CalculatorTest {

    @Test
    void testDivideByZeroThrowsExceptionWithMessage() {
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
            Calculator.divide(10, 0);
        });
        assertEquals("Cannot divide by zero", exception.getMessage());
    }
}

class Calculator {
    public static int divide(int a, int b) {
        if (b == 0) {
            throw new IllegalArgumentException("Cannot divide by zero");
        }
        return a / b;
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Calls Calculator.divide(10, 0)Method invoked with divisor zero-PASS
3Calculator.divide throws IllegalArgumentException with message 'Cannot divide by zero'Exception thrown and caught by assertThrowsException type is IllegalArgumentExceptionPASS
4Assert exception message equals 'Cannot divide by zero'Exception message retrievedassertEquals("Cannot divide by zero", exception.getMessage())PASS
5Test ends successfullyTest passed with expected exception and message-PASS
Failure Scenario
Failing Condition: Calculator.divide does not throw exception or throws with wrong message
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify about the exception?
AThe exception type and its message
BOnly that an exception is thrown
CThat no exception is thrown
DThat the method returns zero
Key Result
Always verify both the type and the message of exceptions to ensure your code fails as expected with clear error information.