Video in progress
How do you wait for the result of an @Async method or a background process in a test, and why is Thread.sleep a bad choice?
Thread.sleep(2000) either waits too long, or isn't enough on a slow CI and the test fails by chance. Instead, with a tool like Awaitility you check at short intervals until the condition holds, and set a maximum time limit.
📖 Answer
The problematic test:
service.importAsync(file);
Thread.sleep(1000); // enough on a laptop, not on CI
assertEquals(500, repo.count());
With Awaitility:
service.importAsync(file);
await().atMost(Duration.ofSeconds(10))
.pollInterval(Duration.ofMillis(100))
.untilAsserted(() -> assertEquals(500, repo.count()));
If the result is ready in 300 ms, the test finishes in 300 ms. If it isn't there in 10 seconds, it fails with a clear message.
Other approaches:
- if the method returns a
CompletableFuture, simplyfuture.get(5, SECONDS)is the cleanest option; - in a unit test, remove the async part entirely: inject the
Executorand give the test a synchronous one (Runnable::run). Then the logic is checked on one thread, deterministically; - checking that "the event did not happen" is hard:
await().during(2, SECONDS).until(...)checks that the condition holds steadily for that whole time.
In Spring, @Async works in the test context as well, so in an integration test Awaitility is almost mandatory.
Sign up to mark studied questions and save your progress.