【问题标题】:How to write assertTimeoutPreemptively (JUnit 5) in JUnit 4?如何在 JUnit 4 中编写 assertTimeoutPreemptively (JUnit 5)?
【发布时间】:2019-10-09 19:52:52
【问题描述】:

到目前为止,我一直在使用 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 条件方面的任何指导?

【问题讨论】:

    标签: java junit junit4 junit5


    【解决方案1】:

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

    在 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() 的行为复制/调整到您自己的项目中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-25
      • 2018-04-03
      • 2019-11-03
      相关资源
      最近更新 更多