javaawaitility

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());

Solution

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