The following test works when I use 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);
}
But if I use Awaitility instead for same test, it throws following error. Why? The code using Awaitility is using atLeast(500 ms).
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);
}
This is a misunderstanding of the API.
The documentation for
atLeastsays:In other words, this test asserts that the condition shouldn't return
truebefore 500 milliseconds have passed — that it should take more than half a second to run — but the condition returnstrueimmediately.If you're trying to assert that the condition returns true in less than 500 milliseconds (the much more common case) you want to use
atMostinstead ofatLeast.If you're simply trying to insert a 500ms pause,
Thread.sleepis a perfectly fine way to do it.