Java - Thread.sleep VS Awaitility.await()

11.4k Views Asked by At

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

There are 3 best solutions below

3
matsev On BEST ANSWER

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

0
SaleemKhair On

Though what you did can make sense from the first look, but with a better understanding of the design of the library there are two apparent principles that you have missed.

The Awaitility library introduces a functional style usage to define properties, conditions, accumulators and transformations.

1. Terminal Operations.


  Awaitility
       .await()
       .atMost(Duration.TWO_SECONDS)

The above code will not execute, because internally what runs the chain is a call to Condition#await which is accessed only by caling ConditionFactory#until.

This call to until can be called a Terminal Operation

2. Intermediate Operations.


Operations like await, atMost , timeout and other operations only return the same instance of ConditionFactory, which will only define behaviour and actions in a lazy manner.

So in a nutshell the design expects you to:

  1. Create an instance of ConditionFactory using Awaitility#await.
  2. Define your await behaviour using the intermediate methods.
  3. Execute and/or transform using until and its variants.
0
pbthorste On

A simple replacement with Awaitility for:

Thread.sleep(200);

could be:

Awaitility.await()
      .pollDelay(Duration.ofMillis(200))
      .until(() -> true);