What if your tests could instantly catch the exact error message your users see?
Why Checking exception message in JUnit? - Purpose & Use Cases
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.
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.
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.
try { divide(10, 0); fail("Expected exception"); } catch (Exception e) { if (!e.getMessage().equals("Cannot divide by zero")) { fail("Wrong message"); } }
assertThrows(ArithmeticException.class, () -> divide(10, 0), "Cannot divide by zero");
You can trust your tests to catch exact error messages, making your software more reliable and user-friendly.
When a banking app prevents a withdrawal that exceeds the balance, checking the exception message ensures the user sees a clear, correct warning.
Manual error message checks are slow and error-prone.
JUnit lets you verify exact exception messages automatically.
This improves test accuracy and saves time.