How can I await at least specified amount of time with Awaitility?

18.8k Views Asked by At

In my test class, I really need to sleep for some amount of time. It's an integration test involving periodic remote call.

for (int i = 0; i < 16; i++) {
    // sleep some... should sleep some...
    Thread.sleep((int) TimeUnit.MINUTES.toMillis(4L)); // means as it means.
    // call remote api and check the response.
}

And what is the equivalent expression using Awaitility?

I tried...

// Let's sleep for 4 minutes, no matter what happen!
Awaitility.await()
        .atLeast(Duration.ofMinutes(4L)) // what the hell does this mean, anyway?
        .untilTrue(new AtomicBoolean(false));

It seems the timeout fired just after the default polling interval.

Shouldn't I use the Awaitillity at the first time in this case?

2

There are 2 best solutions below

0
quick response On BEST ANSWER

Probably too late of an answer but there are several ways to do it.

This tells awaitility to have a poll delay of 4 minutes. So, wait 4 minutes before doing the assertion.

Awaitility
    .await()
    .pollDelay(4, TimeUnit.MINUTES)
    .untilAsserted(() -> Assert.assertTrue(true));
0
Hobgoblin On

Also quite late, with the latest Awaitility (4.2.0) a timeout also needs to be defined, which needs to be larger than the pollDelay. Default timeout is 10 seconds. So, if you wait less then 10sec, not timeout definition necessary.

So, this worked for me:

Awaitility.await()
  .timeout(66, SECONDS)
  .pollDelay(65, SECONDS)
  .untilAsserted(() -> Assertions.assertTrue(true));

worked in a test without multi-threading, replacing a Thread.sleep(x).