使用 Awaitility 来确定某些事情没有发生

Dam*_*amo 14 java kotlin awaitility

有没有办法使用 Awaitility 来断言没有任何改变?我想验证某个主题是否未被写入,但由于没有状态更改,Awaitility 不喜欢这样。例如,这段代码给出了以下错误。谢谢

    @Test
    fun waitUntilListMightBePopulated() {

        val myTopic: List<String> = emptyList()

        await.atLeast(2, TimeUnit.SECONDS).pollDelay(Duration.ONE_SECOND).until {
            myTopic.isEmpty()
        }
    }
Run Code Online (Sandbox Code Playgroud)
ConditionTimeoutException: Condition was evaluated in 1005478005 NANOSECONDS which is earlier than expected minimum timeout 2 SECONDS
Run Code Online (Sandbox Code Playgroud)

ahm*_*l88 14

是的,您可以使用during方法来验证。
从 Awaitility 4.0.2 版本开始支持。

例如:
在下面的例子中,我们将验证在10秒内,主题将保持为空[未更改]。

await()
    .during(Duration.ofSeconds(10)) // during this period, the condition should be maintained true
    .atMost(Duration.ofSeconds(11)) // timeout
    .until (() -> 
        myTopic.isEmpty()           // the maintained condition
    );
Run Code Online (Sandbox Code Playgroud)

提示:
很明显,during超时持续时间应该小于超时atMost持续时间[或DefaultTimeout值],否则,测试用例将失败并抛出ConditionTimeoutException


小智 1

当达到超时时,Awaitility 会抛出 ConditionTimeoutException。检查在预定时间内没有任何更改的一种方法是查找更改并断言抛出异常。

请注意,该解决方案非常慢,因为成功结果的等待时间很短,并且存在与抛出异常相关的缺点(What are theeffects of exceptions on performance in Java?)。

@Test
public void waitUntilListMightBePopulated() {
    List<String> myTopic = new ArrayList<>();

    Assertions.assertThrows(ConditionTimeoutException.class,
        () -> await()
                .atMost(Duration.ofSeconds(2))
                .until(() -> myTopic.size() > 0)
    );
}
Run Code Online (Sandbox Code Playgroud)