Video in progress
In the service below, when rebuildAll() is called, does build() really run asynchronously, and which test catches that?
@Service
class ReportService {
@Async
public CompletableFuture<Report> build(long userId) { ... }
public void rebuildAll(List<Long> ids) {
ids.forEach(this::build); // what happens?
}
}
No: this::build bypasses the Spring proxy, so build runs synchronously on the calling thread. A plain unit test has no proxy and won't see this; only a test with a Spring context catches it, for example one that checks the name of the thread it ran on.
📖 Answer
@Async works through the proxy: when another bean calls reportService.build(1L), the proxy hands the task to the executor. When this.build(...) is called from inside the class, the call never touches the proxy; it's an ordinary Java method call. As a result rebuildAll builds 1000 reports one after another on the request thread, and the endpoint times out.
Two layers of testing:
Logic. A plain unit test with new ReportService(...), checking the result of build(1L).join(). No Spring is needed, but this test says nothing about asynchrony.
Whether it's really asynchronous. In @SpringBootTest you can check that the method runs on a thread other than the caller's:
@Test
void runsOnExecutorThread() {
String caller = Thread.currentThread().getName();
Report r = reportService.build(1L).join();
assertThat(r.threadName()).isNotEqualTo(caller);
}
If you write the same kind of test for rebuildAll, it fails and exposes the self-invocation problem. The fix is to move the asynchronous part into a separate bean, or to call it through another bean inside rebuildAll.
If the side effect of the asynchronous call matters to you (writing to the database), I use await().untilAsserted(...).
Some teams put @Bean(name = "taskExecutor") Executor exec() { return new SyncTaskExecutor(); } in the test profile. That makes the test deterministic, but then race conditions and the loss of ThreadLocal state (SecurityContext, MDC, the transaction) become completely invisible. That's why I keep at least one such test running on a real pool.
Sign up to mark studied questions and save your progress.