Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Thread.sleep VS Awaitility.await()

I'd like to replace Thread.sleep with Awaitility.await(),ideally with minimal changes, as I'm going over Sonar bugs in an older repository. I'm attempting to avoid usage of until of Awaitility, and it is not working out. I understand Awaitility is for async behavior and until function is a big part of it. I'm hoping someone with more experience with Awaitility could suggest a clean usage of it in this test scenario, much appreciate your input.

//Thread.sleep(1000);
Awaitility.await().atMost(Duration.ONE_SECOND);
list = client.getLocation();
Assertions.assertFalse(list.isEmpty());
like image 576
user2917629 Avatar asked Apr 14 '26 01:04

user2917629


2 Answers

A simple replacement with Awaitility for:

Thread.sleep(200);

could be:

Awaitility.await()
      .pollDelay(Duration.ofMillis(200))
      .until(() -> true);
like image 181
pbthorste Avatar answered Apr 16 '26 15:04

pbthorste


Despite your intention, I encourage you to give Awaitility and until() another try. The example below test the same thing in a single one-liner (albeit it is written in several lines for improved readability):

@Test
void test_refresh() {
    Awaitility
       .await()
       .atMost(5, TimeUnit.SECONDS)
       .until(() -> { 
           List<Trp> trpList = client.getAllTrps();
           return !trpList.isEmpty();
       });
}

For more fine grained control of the polling you can take a look at methods like pollInterval() and pollDelay().

like image 27
matsev Avatar answered Apr 16 '26 14:04

matsev