Coding⏱️ 3 min read📅 2026-06-03

How to Fix: How do I assert my exception message with JUnit Test annotation?

JUnit test annotation for asserting exception message

Quick Answer: Use the @ExpectingException annotation with a custom ExpectedException class to assert the exception message in JUnit tests.

Write paragraph 1 explaining the error and who it affects.

Write paragraph 2 explaining why it's frustrating and what we will do.

⚠️ Common Causes

  • Write the first main reason why this error happens in detail.
  • Write the second alternative reason if applicable.

🚀 How to Resolve This Issue

How to assert exception message with JUnit Test annotation

  1. Step 1: Use the @ExpectationFailure annotation from org.junit.jupiter.api
  2. Step 2: or use a custom assertion method
  3. Step 3: that accepts both the expected exception type and its message.
  4. Step 4: For example: @Test(expected = RuntimeException.class, message = "Employee ID is null") public void shouldThrowRuntimeExceptionExce
  5. Step 5: To achieve similar functionality in Java world as .NET does.
  6. Step 6: Use third-party libraries like JUnit-4 or org.junit.vintage
  7. Step 7: or implement a custom assertion method using JUnit 5's @AssertAll annotation.
  8. Step 8: For example: @Test @RepeatedTest(3) public void testSomething() {
  9. Step 9: for (int i = 0; i < 3; i++) {
  10. Step 10: assertThrows(RuntimeException.class, () -> {
  11. Step 11: // Code that throws RuntimeException with null Employee ID
  12. Step 12: });
  13. Step 13: assertEquals("Employee ID is null", "Expected exception message.");
  14. Step 14: }
  15. Step 15: }
  16. Step 16: Conclusion: The JUnit framework does not provide a built-in way to assert the exception message along with the expected exception type.
  17. Step 17: However, there are alternative solutions using third-party libraries or implementing custom assertion methods.

Alternative Advanced Fix

    🎯 Final Words

    Did this fix your problem?

    If not, try searching for specific error codes.

    🔍 Search Error Database

    ❓ Frequently Asked Questions