从@RunWith 过渡到@ExtendWith

transition from @RunWith to @ExtendWith

我需要 JUnit5JUnit4methodInvoker 来将测试本身的执行包装在 lambda 表达式中。像 AfterTestExecutionCallback 这样的给定接口将不允许自己操纵执行。请指导我 JUnit 4 到 5 迁移?从 @RunWith@ExtendWith 的过渡。如何使用 JUnit 5 包装测试本身的执行?

谢谢

您可以通过实施和注册 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;
        }
    }
}

复制自https://junit.org/junit5/docs/current/user-guide/#extensions-intercepting-invocations

看起来您的用例可能是动态测试的候选对象,又名 Testlestshttps://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests -- 您试过了吗?