0
0
JUnittesting~3 mins

Why Checking exception message in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your tests could instantly catch the exact error message your users see?

The Scenario

Imagine you are testing a program manually and want to make sure it shows the right error message when something goes wrong, like dividing by zero.

You run the program, see the error popup, and try to remember the exact message to check later.

The Problem

Manually checking error messages is slow and easy to forget or misread.

You might miss small differences in wording that matter, or spend too much time repeating the same checks.

The Solution

Using JUnit to check exception messages automatically catches the exact error text during tests.

This saves time, avoids mistakes, and makes sure your program tells users the right thing when errors happen.

Before vs After
Before
try {
  divide(10, 0);
  fail("Expected exception");
} catch (Exception e) {
  if (!e.getMessage().equals("Cannot divide by zero")) {
    fail("Wrong message");
  }
}
After
assertThrows(ArithmeticException.class, () -> divide(10, 0), "Cannot divide by zero");
What It Enables

You can trust your tests to catch exact error messages, making your software more reliable and user-friendly.

Real Life Example

When a banking app prevents a withdrawal that exceeds the balance, checking the exception message ensures the user sees a clear, correct warning.

Key Takeaways

Manual error message checks are slow and error-prone.

JUnit lets you verify exact exception messages automatically.

This improves test accuracy and saves time.