5.11. Intercepting Invocations

[InvocationInterceptor](https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/extension/InvocationInterceptor.html) defines the API for Extensions that wish to intercept calls to test code.

The following example shows an extension that executes all test methods in Swing’s Event Dispatch Thread.

An extension that executes tests in a user-defined thread

  1. public class SwingEdtInterceptor implements InvocationInterceptor {
  2. @Override
  3. public void interceptTestMethod(Invocation<Void> invocation,
  4. ReflectiveInvocationContext<Method> invocationContext,
  5. ExtensionContext extensionContext) throws Throwable {
  6. AtomicReference<Throwable> throwable = new AtomicReference<>();
  7. SwingUtilities.invokeAndWait(() -> {
  8. try {
  9. invocation.proceed();
  10. }
  11. catch (Throwable t) {
  12. throwable.set(t);
  13. }
  14. });
  15. Throwable t = throwable.get();
  16. if (t != null) {
  17. throw t;
  18. }
  19. }
  20. }