如果测试超时,有没有办法从 JUnit5 获得回调?

问题描述

在 JUnit 4 中,我们过去必须使用 Timeout 规则,如果我们希望它超时,我们会明确地进行测试。 (实际上,我们最终将它放在所有测试的基类上,因为我们总是希望测试超时。)

这导致我们最终自定义Timeout 规则,以便在它中断测试之前记录其堆栈跟踪。

在 JUnit 5 中,超时现在始终处于活动状态(万岁),但我正在考虑如何在测试超时之前添加堆栈跟踪记录。

是否有某种拦截点或扩展在测试超时之前被称为,我们可以挂在 at 记录附加信息?

解决方法

我认为没有任何方法可以在测试超时之前立即执行,但是您可以实现一个 TestExecutionExceptionHandler 来检查 TimeoutException 和用它做点什么。

例如,您可以如下分析/打印 InterruptedException 中的 suppressed TimeoutException

class TimedOutTests {

    @RegisterExtension
    TestExecutionExceptionHandler timeoutExceptionHandler = (context,throwable) -> {
        if (throwable instanceof TimeoutException && throwable.getSuppressed().length > 0
                && throwable.getSuppressed()[0] instanceof InterruptedException) {
            throwable.getSuppressed()[0].printStackTrace(System.out);
        }
        throw throwable;
    };

    @Test
    @Timeout(value = 100,unit = MILLISECONDS)
    void takesTooLong() throws Exception {
        Thread.sleep(500);
    }

}

有关更多详细信息,请随时查阅 org.junit.jupiter.engine.extension.TimeoutInvocation 的实现。