0
0
JUnittesting~5 mins

Checking exception message in JUnit

Choose your learning style9 modes available
Introduction

We check exception messages to make sure the error is exactly what we expect. This helps catch bugs and confirm the program handles problems correctly.

When testing that a method throws an error for bad input.
When verifying the error message is clear and helpful to users.
When ensuring the program stops at the right place during failures.
When debugging to confirm the cause of a failure.
When writing tests for code that should prevent invalid actions.
Syntax
JUnit
assertThrows(ExpectedException.class, () -> {
    // code that should throw
});

// To check message:
Exception exception = assertThrows(ExpectedException.class, () -> {
    // code that should throw
});
assertEquals("Expected message", exception.getMessage());

Use assertThrows to check if an exception is thrown.

Capture the exception object to check its message with getMessage().

Examples
This checks that parsing a non-number string throws IllegalArgumentException.
JUnit
assertThrows(IllegalArgumentException.class, () -> {
    Integer.parseInt("abc");
});
This checks the exception message matches exactly what we expect.
JUnit
Exception exception = assertThrows(NumberFormatException.class, () -> {
    Integer.parseInt("abc");
});
assertEquals("For input string: \"abc\"", exception.getMessage());
Sample Program

This test throws an IllegalArgumentException with a message. It then checks the message is exactly "Invalid input provided".

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

public class ExceptionMessageTest {

    @Test
    void testExceptionMessage() {
        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
            throw new IllegalArgumentException("Invalid input provided");
        });
        assertEquals("Invalid input provided", exception.getMessage());
    }
}
OutputSuccess
Important Notes

Always check the exception type first before checking the message.

Exception messages should be clear and helpful for debugging.

Use exact string matching for messages to avoid false positives.

Summary

Use assertThrows to test exceptions.

Capture the exception to check its message with getMessage().

Checking messages helps confirm the exact error cause.