[英]How to write assertTimeoutPreemptively (JUnit 5) in JUnit 4?
到目前為止,我正在使用 JUnit 5,現在我必須使用 JUnit 4 的舊系統,我無法在那里更新 JUnit5。 我在 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()中的行為復制/調整到您自己的項目中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.