RanjR
RanjR

Reputation: 65

Awaitility in java

I am trying to write up a scenario for my integration testing using Awaitility package in java.

I have a call as below:

System.out.println(...)
await().atMost(10,Duration.SECONDS).until(myFunction());
and some code here....

Here, it waits for 10 seconds until the myFunction() is called.

I want something like this,my requirement is: It should keep calling myFunction() for every second for a duration of 10 seconds. Is there any better approach for this?

Upvotes: 3

Views: 19391

Answers (2)

Anya Shenanigans
Anya Shenanigans

Reputation: 94749

The default poll interval for awaitility is 100 milliseconds (i.e. 0.1 of a second). It's documented under Polling in the wiki.

If you want to set the poll interval to a second, then add it to the await:

with().pollInterval(Duration.ONE_SECOND).await().atMost(Duration.TEN_SECONDS).until(myFunction());

This should accomplish the polling once a second for up to 10 seconds.

Here's a very simple example:

import static org.awaitility.Awaitility.*;
import org.awaitility.Duration;
import java.util.concurrent.Callable;

public class Test {

    private Callable<Boolean> waitmeme(int timeout) {
        return new Callable<Boolean>() {
            int counter = 0;
            int limit = timeout;
            public Boolean call() throws Exception {
                System.out.println("Hello");
                counter++;
                return (counter == limit);
            }
        };
    }

    public void runit(int timeout) {
        try {
            with().pollInterval(Duration.ONE_SECOND)
                  .await()
                  .atMost(Duration.TEN_SECONDS)
                  .until(waitmeme(timeout));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) throws Exception {
        int timeout = 11;
        if (args.length >= 1)
            timeout = Integer.parseInt(args[0]);
        new Test().runit(timeout);
    }
}

Upvotes: 5

user2575725
user2575725

Reputation:

it should keep calling myFunction() for every second for a duration of 10 seconds

Why not just use Thread.sleep() instead?

for(int i=1;10>=i;i++){
   myFunction();
   try{
      Thread.sleep(1000);
   }catch(InterruptedException e){
      System.out.println('Thread was interrupted!');
   }
}

Upvotes: -1

Related Questions