How to Use Awaitility for Asynchronous Tests Without Sleeps
Test asynchronous code with Awaitility instead of Thread.sleep: await until a condition holds, tune timeouts and poll intervals, and avoid flaky waits.

Asynchronous code finishes later: a message handler, a scheduled job, a CompletableFuture. A test that checks the result right away fails, and one that sleeps for two seconds passes slowly and still fails on a slow CI machine. Awaitility waits for the condition instead. This uses Awaitility 4 with JUnit Jupiter 6 and AssertJ on JDK 25. Why sleeps break tests is also covered in flaky tests.
Setup
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>4.3.0</version>
<scope>test</scope>
</dependency>Spring Boot's dependency management includes Awaitility, so the version can be omitted in a Boot project.
The basic wait
@Test
void emailIsSentAfterOrderIsPlaced() {
orders.place(newOrder());
await().atMost(5, SECONDS).untilAsserted(() ->
assertThat(mailbox.received()).extracting(Mail::subject).contains("Order confirmed"));
}untilAsserted runs the lambda repeatedly; an AssertionError means "not yet", and the wait ends when the block completes without one. If the five seconds pass, the last assertion error is reported, so the failure shows what was actually in the mailbox. With the default poll interval of 100 ms, a result that arrives after 30 ms costs 100 ms, not a fixed two seconds.
Waiting on a value
await().atMost(Duration.ofSeconds(3))
.pollInterval(Duration.ofMillis(50))
.until(counter::get, greaterThanOrEqualTo(10));
await().until(() -> repository.count() == 3);
await().atMost(2, SECONDS).until(future::isDone);The second argument form takes a Hamcrest matcher, see Hamcrest. The boolean form is the simplest, but its failure message is just "condition was not fulfilled". Use untilAsserted or add .alias("three orders saved") to name it:
await().alias("orders saved").until(() -> repository.count() == 3);Tuning
| Setting | Use |
|---|---|
atMost | Upper limit, make it generous on CI but finite |
pollInterval | How often to check, shorter for cheap conditions |
pollDelay | Wait before the first check |
during | Require the condition to hold for a period (with atLeast) |
ignoreExceptions() | Treat exceptions from the condition as "not yet", for example a connection refused while a service starts |
A project-wide default avoids repeating the timeout:
@BeforeAll
static void configure() {
Awaitility.setDefaultTimeout(Duration.ofSeconds(10));
Awaitility.setDefaultPollInterval(Duration.ofMillis(50));
}Testing that something does not happen
await().during(500, MILLISECONDS).atMost(1, SECONDS)
.until(() -> mailbox.received().isEmpty());during asserts the condition stays true. Negative tests need a time window, and are inherently slower; keep them few.
With Spring and messaging
Consumers in a @SpringBootTest run on listener threads, so wait for their effect. For Kafka tests, poll the database or a captured list, per testing Kafka consumers. Prefer synchronisation tools if you control the code: a CountDownLatch injected through a test double signals completion exactly, see CountDownLatch. Awaitility is for when you cannot.
What to avoid
Huge timeouts. A 60 second atMost turns a real failure into a minute of waiting per test. Choose the time it should take, times a safety factor.
Waiting on shared state across tests. One test's leftover rows satisfy another's wait. Isolate data.
Asserting speed. A wait that passes does not prove the system is fast enough.
Polling with side effects. The condition may run dozens of times, so it must be read only.
A complete test you can copy
The earlier snippets are fragments. This is a whole test class for a service that processes jobs on an executor, with the imports a reader needs. The service hands work to a thread and returns immediately, which is exactly the shape that makes a plain assertion fail.
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
class JobServiceTest {
static class JobService {
private final ExecutorService pool = Executors.newFixedThreadPool(2);
final AtomicInteger processed = new AtomicInteger();
void submit(int count) {
for (int i = 0; i < count; i++) {
pool.submit(() -> {
try { Thread.sleep(50); } catch (InterruptedException e) { return; }
processed.incrementAndGet();
});
}
}
}
@Test
void everySubmittedJobIsProcessed() {
var service = new JobService();
service.submit(6);
assertThat(service.processed.get()).isLessThan(6); // still running right after submit
await().atMost(5, SECONDS)
.untilAsserted(() -> assertThat(service.processed.get()).isEqualTo(6));
}
}The first assertion documents the race: immediately after submit, the work has not finished. The await ends as soon as the sixth job completes, about 150 ms later on two threads, rather than after a fixed sleep chosen to be safe on the slowest machine. AtomicInteger is deliberate. The condition runs on a different thread from the test method, so a plain int field may never show the new value.
The condition runs on another thread
By default Awaitility evaluates the condition on its own polling thread, not on the test thread. Two consequences follow. State the condition reads must be safely published, with volatile, an atomic or a concurrent collection, or the test passes on one machine and times out on another. And thread-bound state, such as a transaction held by the test thread or a ThreadLocal, is invisible inside the lambda.
When the condition must read thread-bound state, switch to the calling thread:
await().pollInSameThread().atMost(2, SECONDS)
.until(() -> entityManager.createQuery("select count(o) from Order o", Long.class)
.getSingleResult() == 3L);pollInSameThread fits tests that run inside a transaction opened by the test, such as Spring's @Transactional tests. Note that a transaction opened on the test thread may not see rows committed by another thread under the default isolation level, so for cross-thread assertions prefer a test that does not wrap itself in a transaction.
Say what you are waiting for when it fails
A timeout without context sends the reader to the source. Name the wait with alias, and log each evaluation while diagnosing a slow condition with a listener.
await().alias("six jobs processed")
.atMost(5, SECONDS)
.conditionEvaluationListener(c ->
System.out.printf("%s after %d ms%n", c.getDescription(), c.getElapsedTimeInMS()))
.untilAsserted(() -> assertThat(service.processed.get()).isEqualTo(6));On a timeout, Awaitility throws ConditionTimeoutException. Making the service process one job and asking for six, with a one second limit, produces this on Awaitility 4.3.0:
org.awaitility.core.ConditionTimeoutException: Condition with alias 'six jobs processed' didn't complete within 1 seconds because assertion condition defined as a Lambda expression in JobServiceTest
expected: 6
but was: 1.The alias names the wait, and the last assertion error says how far it got. but was: 1 tells you the pipeline is slow or stalled, not that it never ran. Remove the listener once the cause is found, since it prints on every poll.
When a latch beats polling
Polling is the right tool when you do not control the code under test. When you do, a CountDownLatch or a callback is exact and faster: the test is released the moment the work finishes, with no poll interval at all.
var done = new CountDownLatch(1);
service.onComplete(job -> done.countDown());
service.submit(job);
assertThat(done.await(5, SECONDS)).as("job completed").isTrue();Use the latch for code you wrote with a hook point, and Awaitility for external effects: a row appearing in a database, a message on a topic, a file on disk. Never use either to check that nothing happened, since an absent event cannot be waited for. Use during with a short window and accept that it proves only that nothing happened in that window.
Pick the timeout for CI, not for your laptop
A five second ceiling that passes locally fails when a shared runner is loaded. The ceiling does not slow a passing test, because the wait ends the moment the condition holds, so set it generously, ten to thirty seconds for integration tests, and fix the poll interval by how expensive the check is. A tight ceiling buys nothing and creates the flakes this library exists to remove.
Where this does not apply
Deterministic code needs no waiting. Make time injectable as in deterministic tests. See the Awaitility wiki and its Javadoc.


