gpt4 book ai didi

java - 在 JUnit 5 中超过超时后如何使测试失败?

转载 作者:行者123 更新时间:2023-12-01 14:05:33 26 4
gpt4 key购买 nike

在 JUnit 4 中,“超时”注释参数可用于强制测试在给定的时间后停止:

@Test(timeout=100)
public void infinity() {
while(true);
}

如何在 JUnit 5 中做到这一点?

密切相关(和代码取自) timeout parameter for Annotation Type Test ,但对于 JUnit 5。

最佳答案

严格等同于 timeout属性是声明性 @Timeout注解。
From the JUnit 5 documentation :

The @Timeout annotation allows one to declare that a test, test factory, test template, or lifecycle method should fail if its execution time exceeds a given duration. The time unit for the duration defaults to seconds but is configurable.



例如 :
@Test
@Timeout(value = 100, unit = TimeUnit.MILLISECONDS)
void infinity() {
// fails if execution time exceeds 100 milliseconds
//...
}

Assertions.assertTimeout() Assertions.assertTimeoutPreemptively() 是 JUnit 5 中引入的新概念(JUnit 4 中不存在)。
这些是 @Timeout 的替代方案将超时范围缩小到一组特定的语句:这些在 Executable 中定义或在 Supplier作为参数传递。
这两种方法(名称非常接近)解决了相同的总体目标,但有细微的差别。 assertTimeoutPreemptively()抢先中止 Executable/Supplier如果超时发生同时 assertTimeout()才不是。
要实现它, assertTimeoutPreemptively()执行提供的 Executable/Supplier在与调用代码不同的线程中,而 assertTimeout()在同一个线程中执行。

来自官方文档的警告:
依赖于 java.lang.ThreadLocal 的代码/库用于测试执行设置/拆卸的存储可能会对 assertTimeoutPreemptively() 产生不良副作用因为它在不同的线程中执行提供的语句。

关于java - 在 JUnit 5 中超过超时后如何使测试失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57116801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com