Annotation Type ExpectedException


@Retention(RUNTIME) @Target(METHOD) public @interface ExpectedException
Annotation for specifying expected exceptions in JUnit 5 tests using JMockit.

This annotation allows you to declare that a test method is expected to throw a specific exception type, optionally with a specific message or message fragment. It is designed to help migrate JMockit-based tests from JUnit 4 to JUnit 5 and flexible message matching.

Usage examples:

// Expect a MissingInvocation exception (type only)
@Test
@ExpectedException(MissingInvocation.class)
public void testMissingInvocation() { ... }

// Expect a MissingInvocation exception with a message containing "missing call"
@Test
@ExpectedException(value = MissingInvocation.class, expectedMessages = {"missing call"})
public void testMissingInvocationWithMessage() { ... }

// Expect either of two message fragments
@Test
@ExpectedException(value = MissingInvocation.class, expectedMessages = {"missing call", "not called"})
public void testMultipleMessages() { ... }

// Use exact message matching
@Test
@ExpectedException(value = MissingInvocation.class, expectedMessages = {"Exact error message"}, messageContains = false)
public void testExactMessage() { ... }

For standard exception assertions unrelated to JMockit, use JUnit 5's assertThrows.

  • Required Element Summary

    Required Elements
    Modifier and Type
    Required Element
    Description
    Class<? extends Throwable>
    Specifies the type of exception expected to be thrown by the test method.
  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    Specifies one or more expected message fragments or exact messages for the exception.
    boolean
    If true, matches exception messages using String.contains; if false, uses String.equals.
  • Element Details

    • value

      Class<? extends Throwable> value
      Specifies the type of exception expected to be thrown by the test method.

      Example:

      &#64;ExpectedException(MissingInvocation.class)
      
      Returns:
      the expected exception class
    • expectedMessages

      String[] expectedMessages
      Specifies one or more expected message fragments or exact messages for the exception.

      If multiple values are provided, the test passes if any fragment matches the exception message.

      Returns:
      array of expected message fragments or exact messages
      Default:
      {}
    • messageContains

      boolean messageContains
      If true, matches exception messages using String.contains; if false, uses String.equals.

      Default is true for compatibility with JUnit 4's contains-style matching.

      Returns:
      true for contains matching; false for exact matching
      Default:
      true