Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 217
Jin Kwon Avatar asked Sep 02 '25 16:09

Jin Kwon


2 Answers

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));
like image 78
quick response Avatar answered Sep 05 '25 05:09

quick response


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).

like image 42
Hobgoblin Avatar answered Sep 05 '25 07:09

Hobgoblin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!