Search code examples
javajunitjunit4junit5

transition from @RunWith to @ExtendWith


I need the methodInvoker of JUnit4 in JUnit5 to wrap the execution of the test itself in a lambda expression. The given Interfaces like AfterTestExecutionCallback will not allow manipulating the execution itself. Kindly guide me with JUnit 4 to 5 migration? The transition from @RunWith to @ExtendWith. How can you wrap the execution of the test itself with JUnit 5?

Thanks

enter image description here


Solution

  • You may do so via implementing and registering an InvocationInterceptor

    public class SwingEdtInterceptor implements InvocationInterceptor {
    
        @Override
        public void interceptTestMethod(Invocation<Void> invocation,
                ReflectiveInvocationContext<Method> invocationContext,
                ExtensionContext extensionContext) throws Throwable {
    
            AtomicReference<Throwable> throwable = new AtomicReference<>();
    
            SwingUtilities.invokeAndWait(() -> {
                try {
                    invocation.proceed();
                }
                catch (Throwable t) {
                    throwable.set(t);
                }
            });
            Throwable t = throwable.get();
            if (t != null) {
                throw t;
            }
        }
    }
    

    Copied from https://junit.org/junit5/docs/current/user-guide/#extensions-intercepting-invocations

    Seems like your use-case might be a candidate for Dynamic Tests, aka Testlests: https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests -- did you give them a try?