0
0
JUnittesting~15 mins

Checking exception message in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify exception message when invalid input is provided
Preconditions (2)
Step 1: Call the method parseNumber with input 'abc'
Step 2: Catch the IllegalArgumentException thrown
Step 3: Verify the exception message is exactly 'Invalid number format'
✅ Expected Result: The test should pass only if the exception is thrown and the message matches 'Invalid number format'
Automation Requirements - JUnit 5
Assertions Needed:
Assert that IllegalArgumentException is thrown
Assert that exception message equals 'Invalid number format'
Best Practices:
Use assertThrows to check for exceptions
Capture the exception object to verify its message
Keep test method names descriptive
Avoid catching exceptions manually inside test
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class NumberParserTest {

    // Method under test
    public int parseNumber(String input) {
        try {
            return Integer.parseInt(input);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid number format");
        }
    }

    @Test
    void testParseNumberThrowsExceptionWithCorrectMessage() {
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
            parseNumber("abc");
        });
        assertEquals("Invalid number format", exception.getMessage());
    }
}

The test method testParseNumberThrowsExceptionWithCorrectMessage uses assertThrows to check that calling parseNumber("abc") throws an IllegalArgumentException. The thrown exception is captured in the exception variable. Then assertEquals verifies the exception message matches exactly "Invalid number format". This approach avoids manual try-catch blocks and clearly expresses the intent to check both the exception type and its message.

The parseNumber method simulates the behavior that throws the exception with the expected message when input is invalid.

Common Mistakes - 3 Pitfalls
Catching exception manually inside test and using fail() instead of assertThrows
Not verifying the exception message, only the exception type
Using assertEquals with exception.toString() instead of getMessage()
Bonus Challenge

Now add data-driven testing with 3 different invalid inputs to verify the exception message each time

Show Hint