How to Test Async Code and Schedulers in Java Reliably
Test async code and schedulers in Java reliably: Awaitility instead of sleep, injectable executors, fake clocks and Spring Async and Scheduled.

Asynchronous code makes tests unreliable in a specific way: the test finishes its setup, starts the work, and then has to decide when to check the result. The reflex answer is Thread.sleep(500), and it fails twice. Make it long and the suite crawls. Make it short and it passes on your laptop and fails on a busy CI agent. The cure is to stop guessing about time. Poll for the outcome, hand the code under test an executor and a clock that the test controls, and call scheduled methods directly. This post shows each technique with Awaitility 4, JUnit 5 and Spring Boot 4 on JDK 25.
Poll with Awaitility
Awaitility waits for a condition to become true, polling at an interval until a timeout. The test takes exactly as long as the work does, and fails with a clear message if it never completes.
@Test
void sends_the_email_after_the_order_is_placed() {
service.place(order);
await().atMost(Duration.ofSeconds(5))
.pollInterval(Duration.ofMillis(50))
.untilAsserted(() -> assertEquals(1, mailbox.sent().size()));
}untilAsserted retries the assertion until it stops throwing, which gives better failure output than until with a boolean: the last assertion error is reported, with the actual value. The 5 seconds is an upper bound, not a delay; a fast run finishes in 50 ms. Pick a timeout that is generous for the slowest CI machine you have, because a flaky timeout costs more than a few extra seconds in the failure case. Awaitility's during and atLeast methods check that a condition holds for a period, which is how you test that nothing happened, for example that no second email is sent. Such tests have to wait, so keep them few.
Never assert on elapsed time. A test that requires an operation to take less than 100 ms fails when the garbage collector pauses; measure performance in a benchmark, not in a unit test.
Return the future
The cleanest design lets the test wait on something the code gives it. If a method starts work and returns a CompletableFuture, the test joins it with a timeout:
@Test
void builds_the_report() throws Exception {
CompletableFuture<Report> future = reports.buildAsync(42L);
Report report = future.get(5, TimeUnit.SECONDS);
assertEquals(42L, report.customerId());
}There is no polling and no sleep, and an exception inside the task surfaces as an ExecutionException from get. Prefer APIs that return a handle for the work over those that return void. When you design a new async method, returning the future costs nothing and makes the test trivial. Composition of futures is in combining futures.
Inject the executor
Code that creates its own thread pool cannot be controlled by a test. Pass the executor in through the constructor, and a test can substitute one that runs tasks on the calling thread:
class Notifier {
private final Executor executor;
Notifier(Executor executor) { this.executor = executor; }
void notifyAll(List<User> users) {
users.forEach(u -> executor.execute(() -> send(u)));
}
}
@Test
void notifies_every_user() {
Executor direct = Runnable::run; // runs inline
var notifier = new Notifier(direct);
notifier.notifyAll(List.of(alice, bob));
assertEquals(2, outbox.size()); // already done, no waiting
}Runnable::run is a direct executor, so the task has completed when execute returns. The test is deterministic, since ordering and timing no longer matter. It tests the logic of the task, not the concurrency. Keep one real-executor test per class to check that the wiring works, and test the logic with the direct one. When thread interleaving is the thing under test, a different approach is needed; see finding race conditions.
Spring @Async
@Async methods run on an executor that Spring configures, so the test calling them returns before the work is done. Two techniques work. Override the executor in the test configuration with a synchronous one:
@TestConfiguration
class SyncAsyncConfig {
@Bean(name = "taskExecutor")
Executor taskExecutor() { return new SyncTaskExecutor(); }
}SyncTaskExecutor runs each task in the calling thread. Or leave it asynchronous and use Awaitility on the side effect. The first is faster, and the second tests more of the real configuration. One trap: @Async is applied through a proxy, so a call from another method of the same class stays synchronous, as in self-invocation. If a test passes because the call was synchronous by accident, the production behaviour was never tested. Also enable async in the test context; a slice test without @EnableAsync ignores the annotation and runs the method inline.
Schedulers and time
Do not wait for a cron expression in a test. Separate the schedule from the work:
@Component
class Cleanup {
private final Clock clock;
private final SessionRepository sessions;
Cleanup(Clock clock, SessionRepository sessions) { this.clock = clock; this.sessions = sessions; }
@Scheduled(cron = "0 0 * * * *")
void purgeExpired() {
sessions.deleteOlderThan(Instant.now(clock).minus(Duration.ofHours(24)));
}
}The test calls purgeExpired() directly, with a Clock.fixed(...), and asserts on the repository. The annotation itself is configuration, and a separate small test can check that the cron string parses (CronExpression.parse("0 0 * * * *")) and that the scheduler is enabled. Time-dependent logic reads from an injected Clock, as covered in the dates post, so no test depends on the wall clock. For code that uses ScheduledExecutorService directly, wrap it in a small interface and replace it with a fake that records the scheduled runnables and lets the test run them. The behaviour of the scheduling support is documented in the Spring scheduling reference.
Latches for callbacks
When the code under test calls back and gives you no future, a CountDownLatch is a deterministic hook:
var done = new CountDownLatch(1);
var received = new AtomicReference<Event>();
bus.subscribe(e -> { received.set(e); done.countDown(); });
publisher.fire();
assertTrue(done.await(5, TimeUnit.SECONDS), "no event arrived");
assertEquals("created", received.get().type());The await with a timeout returns false on failure, and the message in assertTrue says what was missing. An await() with no timeout hangs the build forever when the event never comes, which is the worst failure mode, so always pass one.
Reactive code
For Reactor, StepVerifier controls virtual time and checks the sequence of signals without sleeping: StepVerifier.withVirtualTime(() -> service.pollEvery(Duration.ofMinutes(5))).thenAwait(Duration.ofMinutes(15)).expectNextCount(3).thenCancel().verify(). Debugging a failing pipeline has its own tooling, in debugging Reactor pipelines.
Avoid flakiness
A flaky async test is a bug report about either the test or the code. Check for four causes. A shared static or singleton that earlier tests leave dirty. A timeout so tight that a garbage collection pause trips it. An assertion on ordering for work that has none. A background thread from a previous test still running. Run the suspect test a thousand times in a loop (@RepeatedTest(1000)) and under CPU stress to reproduce the failure, and fix the cause rather than adding a retry, since a retry hides a race that will bite in production.
A note on timeouts in CI
Timeouts that pass on a laptop fail on a shared CI runner that is busy with other jobs. Read the limit from a system property or an environment variable, so CI can raise it without changing code, and keep the local default short so that a genuine hang fails quickly during development. Record the slowest observed time of each asynchronous test in the build output; a test that takes four seconds against a five-second limit is a flaky test that has not failed yet.
When this does not apply
Tests of real concurrency, such as lock behaviour or visibility, cannot use a direct executor, because the interleaving is the subject. Those need stress tools like jcstress. The library usage is described in the Awaitility wiki.


