Unit tests Spring @Scheduled and @Async methods using JUnit 5, CompletableFuture, Awaitility, Mockito. Covers cron jobs, background tasks, thread pools, retries without real scheduling.
From developer-kit-javanpx claudepluginhub giuseppe-trisciuoglio/developer-kit --plugin developer-kit-javaThis skill is limited to using the following tools:
references/examples.mdSearches, retrieves, and installs Agent Skills from prompts.chat registry using MCP tools like search_skills and get_skill. Activates for finding skills, browsing catalogs, or extending Claude.
Searches prompts.chat for AI prompt templates by keyword or category, retrieves by ID with variable handling, and improves prompts via AI. Use for discovering or enhancing prompts.
Provides Ktor server patterns for routing DSL, plugins (auth, CORS, serialization), Koin DI, WebSockets, services, and testApplication testing.
@Scheduled and @Async MethodsPatterns for unit testing Spring @Scheduled and @Async methods with JUnit 5. Test CompletableFuture results, use Awaitility for race conditions, mock scheduled task execution, and validate error handling — without waiting for real scheduling intervals.
@Scheduled method logic@Async method behaviorCompletableFuture results@Async methods directly — bypass Spring's async proxy; the annotation is irrelevant in unit tests@Mock and @InjectMocks (Mockito)CompletableFuture.get(timeout, unit) or await().atMost(...).untilAsserted(...)@Scheduled methods directly — do not wait for cron/fixedRate; the annotation is ignored in unit testsExecutionException wrapping on CompletableFuture.get()Validation checkpoints:
CompletableFuture.get(), assert the returned value before verifying mock interactionsExecutionException is thrown, check .getCause() to identify the root exceptionatMost() duration or reduce pollInterval() until the condition is reachableverify() callsKey patterns — complete examples in references/examples.md:
// @Async: call directly, wait with CompletableFuture.get(timeout, unit)
@Service
class EmailService {
@Async
public CompletableFuture<Boolean> sendEmailAsync(String to) {
return CompletableFuture.supplyAsync(() -> true);
}
}
@Test
void shouldReturnCompletedFuture() throws Exception {
EmailService service = new EmailService();
Boolean result = service.sendEmailAsync("test@example.com").get(5, TimeUnit.SECONDS);
assertThat(result).isTrue();
}
// @Scheduled: call directly, mock the repository
@Component
class DataRefreshTask {
@InjectMocks private DataRepository dataRepository;
@Scheduled(fixedDelay = 60000) public void refreshCache() { /* ... */ }
}
@Test
void shouldRefreshCache() {
when(dataRepository.findAll()).thenReturn(List.of(new Data(1L, "item1")));
dataRefreshTask.refreshCache();
verify(dataRepository).findAll();
}
// Awaitility: use for race conditions with shared mutable state
@Test
void shouldProcessAllItems() {
BackgroundWorker worker = new BackgroundWorker();
worker.processItems(List.of("item1", "item2", "item3"));
Awaitility.await()
.atMost(Duration.ofSeconds(5))
.pollInterval(Duration.ofMillis(100))
.untilAsserted(() -> assertThat(worker.getProcessedCount()).isEqualTo(3));
}
// Mocked dependencies with exception handling
@Test
void shouldHandleAsyncExceptionGracefully() {
doThrow(new RuntimeException("Email failed")).when(emailService).send(any());
CompletableFuture<String> result = service.notifyUserAsync("user123");
assertThatThrownBy(result::get)
.isInstanceOf(ExecutionException.class)
.hasCauseInstanceOf(RuntimeException.class);
}
Full Maven/Gradle dependencies, additional test classes, and execution count patterns: see references/examples.md.
CompletableFuture.get() to prevent hanging tests@Scheduled logic directly — the annotation is ignored in unit testsCompletableFuture.get()@Async self-invocation: calling @Async from another method in the same class executes synchronously — the Spring proxy is bypassedThreadPoolTaskScheduler does not guarantee execution orderatMost(); infinite waits hang the test suite@Scheduled is ignored in unit tests — call methods directly@Async Documentation@Scheduled Documentationreferences/examples.md