首页 > 解决方案 > 在并行测试环境中使用 StepVerifier

问题描述

在并行测试环境中使用 StepVerifierwithVirtualTime和方法时遇到了一些麻烦。create

private static final Duration DELAY = Duration.ofSeconds(1);

public void testA() {
    StepVerifier.withVirtualTime(() -> Mono.just(1).delayElement(DELAY))
            .thenAwait(DELAY)
            .expectNext(1)
            .expectComplete()
            .verify();
}

public void testB() {
    StepVerifier.create(Mono.just(1).delayElement(DELAY))
            .thenAwait(DELAY)
            .expectNext(1)
            .expectComplete()
            .verify();
}

Maven Surefire 插件配置:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
    <configuration>
        <groups>unit</groups>
        <includes>
            <include>**/*Test.java</include>
        </includes>
        <parallel>methods</parallel>
        <threadCount>2</threadCount>
        <trimStackTrace>false</trimStackTrace>
    </configuration>
</plugin>

这些测试失败,但有以下异常(GitHub 上提供的完整堆栈跟踪,请参阅下面的链接。):

[ERROR] testA(com.github.hisener.StepVerifierTest)  Time elapsed: 0.04 s  <<< FAILURE!
java.lang.NullPointerException: timedScheduler
    at java.base/java.util.Objects.requireNonNull(Objects.java:246)
[ERROR] testB(com.github.hisener.StepVerifierTest)  Time elapsed: 0.043 s  <<< FAILURE!
reactor.core.Exceptions$ReactorRejectedExecutionException: Scheduler unavailable
    at reactor.core.Exceptions.failWithRejected(Exceptions.java:249)

例如,我认为它与delayElements以下测试之一无关,timeout它们也失败了:

public void testA() {
    StepVerifier.withVirtualTime(() -> Mono.just(1)).expectNext(1).expectComplete().verify();
}

public void testB() {
    StepVerifier.create(Mono.just(1).timeout(DELAY)).expectNext(1).expectComplete().verify();
}

我已经在 TestNG 和 Junit 5 上进行了测试,但没有运气。代码可在 GitHub 上获得:

标签: project-reactor

解决方案


StepVerifier#withVirtualTime用虚拟时间替换所有默认调度程序,因此并行使用它不是一个好主意


推荐阅读