gpt4 book ai didi

java - 如何在 JUnit 4 中编写assertTimeoutPreemptively (JUnit 5)?

转载 作者:行者123 更新时间:2023-12-01 23:24:19 25 4
gpt4 key购买 nike

到目前为止,我一直在使用 JUnit 5,现在我必须在使用 JUnit 4 的旧系统上工作,并且无法在那里更新 JUnit 5。我在 JUnit 5 中有一个测试,必须在 JUnit 4 中编写,但我不确定它将如何工作或如何编写?下面是JUnit 5版本的测试。

@AfterEach
void afterEach() throws Exception {
// Bleed off any events that were generated...
assertTimeoutPreemptively(ofMillis(MESSAGE_CLEARING_TIMEOUT_MS), () -> {
boolean tryAgain = true;
while (tryAgain) {
try {
final IMessageFacade message = messageConsumer.receiveMessage(MESSAGE_TIMEOUT_MS);
message.acknowledge();
} catch (MessagingException e) {
tryAgain = false;
}
}
});
broker.stop();
}

在测试中,我使用 assertTimeoutPreemptively() 并且不确定如何将其转换为 JUnit 4。我尝试在 JUnit 4 中设置一个全局超时,但没有成功工作。关于使用 JUnit 4 编写上述 @AfterEach 条件有什么指导吗?

最佳答案

断言不应该只运行一次吗?在测试拆解中找到断言有点令人惊讶。考虑将您的断言作为测试的一部分。

在 JUnit 5 中,这看起来像:

import static java.util.concurrent.TimeUnit.MILLISECONDS;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;

public class TimeoutJUnit5Test {

@Test @Timeout(value = 10, unit = MILLISECONDS)
void junitFiveTimeout() {
// ...
}
}

在 JUnit 4 中:

import org.junit.Test;

public class TimeoutJUnit4Test {

@Test(timeout = 10)
public void junitFourTimeout() {
// ...
}
}

是什么阻止您使用这两个版本的 JUnit? (pom.xml):

        <dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>

最后一个选项是简单地复制/调整新 JUnit 5 assertTimeoutPreemptively() 中的行为。到您自己的项目。

关于java - 如何在 JUnit 4 中编写assertTimeoutPreemptively (JUnit 5)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58311353/

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