You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Awaitility替代Thread.sleep()触发最小等待时长报错的原因

问题描述

当使用Thread.sleep()时,以下测试用例可正常运行:

@Test
public void closeableTimer() throws InterruptedException {
  Timer timer = new DefaultTimer(TimeUnit.NANOSECONDS);
  Assertions.assertThat(timer.count()).isEqualTo(0);
  Assertions.assertThat(timer.totalDuration()).isEqualTo(Duration.ZERO);
  try (Timer.Timed sample = timer.start()) {
    Thread.sleep(500L);
  }
  Assertions.assertThat(timer.count()).isEqualTo(1);
  Assertions.assertThat(timer.totalDuration()).isGreaterThan(Duration.ZERO);
} 

但改用Awaitility并设置atLeast(Duration.ofMillis(500L))执行相同测试时,却抛出如下错误:

Condition was evaluated in 108 milliseconds which is earlier than
expected minimum timeout 500 milliseconds
org.awaitility.core.ConditionTimeoutException

对应测试代码如下:

@Test
public void closeableTimer() {
  Timer timer = new DefaultTimer(TimeUnit.NANOSECONDS);
  Assertions.assertThat(timer.count()).isEqualTo(0);
  Assertions.assertThat(timer.totalDuration()).isEqualTo(Duration.ZERO);
  try (Timer.Timed ignored = timer.start()) {
    await().atLeast(Duration.ofMillis(500L)).until(() -> true);
  }
  Assertions.assertThat(timer.count()).isEqualTo(1);
  Assertions.assertThat(timer.totalDuration()).isGreaterThan(Duration.ZERO);
}
报错原因

atLeast()的作用是强制要求等待时长至少达到指定值,但你传入的条件() -> true是一个会立即返回true的表达式——Awaitility会第一时间判定条件满足,此时实际等待时长远小于你设置的500毫秒,触发了Awaitility的校验逻辑,因此抛出ConditionTimeoutException。

简单来说:你要求必须等够500毫秒,但你的条件根本不需要等待就满足了,两者冲突导致报错。

如果想用Awaitility实现类似Thread.sleep()的固定等待效果,应该改用pollDelay()方法,代码示例:

await().pollDelay(Duration.ofMillis(500L)).until(() -> true);

内容的提问来源于stack exchange,提问作者kar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:27:41