java - 从 @RunWith 过渡到 @ExtendWith

标签 java junit junit4 junit5

我需要methodInvokerJUnit4JUnit5将测试本身的执行包装在 lambda 中表达。给定的接口(interface)(例如 AfterTestExecutionCallback)将不允许操纵执行本身。请指导我 JUnit 4到5迁移?从 @RunWith 的转变至@ExtendWith 。如何使用 JUnit 5 包装测试本身的执行?

谢谢

enter image description here

最佳答案

您可以通过实现和注册一个InitationInterceptor来实现这一点

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

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

关于java - 从 @RunWith 过渡到 @ExtendWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58728649/

相关文章:

java - 使用 InSequence 注释时出现 arquillian UnsupportedOperationException

java - 在单元测试期间在应用程序类中出错

java - catch block 后如何询问用户输入

java - 当我在非事务中使用事务bean时,Spring会建立与数据库的连接吗?

java - JUnit:当测试的类不包含方法时,类方法的测试会中断编译

java - @RunWith(DataProvider.class) 时 @Before 不会被执行

java - java中如何生成随机整数?

java - 使用 randomElement() 方法编写 Set 实现

Java/JUnit - AssertTrue 与 AssertFalse

java - 如何比较同一数组中的两个元素?