1

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);
  }
kar
  • 4,791
  • 12
  • 49
  • 74

1 Answers1

1

This is a misunderstanding of the API.

The documentation for atLeast says:

In case the condition is fulfilled before the duration specified by atLeast an exception is thrown indicating that the condition shouldn't be completed earlier than the specified duration.

In other words, this test asserts that the condition shouldn't return true before 500 milliseconds have passed — that it should take more than half a second to run — but the condition returns true immediately.

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 atMost instead of atLeast.

If you're simply trying to insert a 500ms pause, Thread.sleep is a perfectly fine way to do it.

Tim Moore
  • 8,958
  • 2
  • 23
  • 34