unit-test-scheduled-async
giuseppe-trisciuoglio/developer-kit
Unit test Spring @Scheduled and @Async methods with JUnit 5, Awaitility, and Mockito without waiting for real scheduling intervals.
What is unit-test-scheduled-async?
Provides patterns for testing Spring background tasks, cron jobs, and async methods using JUnit 5, CompletableFuture, Awaitility, and Mockito. Use when you need to verify scheduled task logic, async execution, exception handling, and thread pool behavior in isolation without relying on actual scheduling delays.
- Call @Async and @Scheduled methods directly in tests, bypassing Spring's async proxy and scheduling annotations
- Wait for async completion using CompletableFuture.get(timeout, unit) or Awaitility with configurable polling
- Mock dependencies with Mockito to isolate task logic and verify execution counts
- Test exception propagation in async methods by catching ExecutionException and inspecting root causes
- Validate cron expression logic and retry behavior without waiting for actual scheduling intervals
- Simulate thread pool behavior and verify task execution order and counts
How to install unit-test-scheduled-async
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill unit-test-scheduled-async- JUnit 5 (Jupiter)
- Mockito for mocking
- Awaitility library for async assertions
- Spring Framework with @Scheduled and @Async support
- Maven or Gradle for dependency management
How to use unit-test-scheduled-async
- 1.Install the skill using the provided npx command
- 2.Review the patterns in references/examples.md for your use case (CompletableFuture, @Scheduled, or @Async)
- 3.Mock all external dependencies using @Mock and @InjectMocks
- 4.Call @Async/@Scheduled methods directly in your test (annotations are ignored in unit tests)
- 5.For @Async methods returning CompletableFuture, use .get(timeout, unit) to wait for completion
- 6.For race conditions, use Awaitility.await().atMost(...).untilAsserted(...) with appropriate polling intervals
- 7.Assert returned values before verifying mock interactions
- 8.Always set a timeout on CompletableFuture.get() to prevent hanging tests
Use cases
- Testing @Async methods that return CompletableFuture with mocked dependencies
- Verifying @Scheduled task logic without waiting for fixedDelay or cron timing
- Testing exception handling in background tasks and async operations
- Validating execution counts and mock interactions after multiple task invocations
- Testing race conditions with shared mutable state using Awaitility polling
- Java developers testing Spring background tasks and scheduled jobs
- QA engineers validating async behavior in Spring applications
- Backend developers building reliable cron jobs and periodic tasks
- Teams using JUnit 5 with Mockito for unit test coverage
unit-test-scheduled-async FAQ
No. Call @Scheduled methods directly in tests; the annotation is ignored. Test the method logic in isolation without waiting for fixedDelay or cron intervals.
Call the method directly and use CompletableFuture.get(timeout, unit) to wait for completion. Always set a timeout to prevent hanging tests. Assert the returned value before verifying mock interactions.
Catch ExecutionException and inspect .getCause() to identify the root exception. Use assertThatThrownBy() to verify the exception type and message.
Use Awaitility only for race conditions with shared mutable state. For simple async methods, prefer direct calls with CompletableFuture.get(). Awaitility polls a condition until it becomes true or times out.
When @Async is called from another method in the same class, the Spring proxy is bypassed and execution is synchronous. Call the method directly in tests to verify logic without relying on the proxy.
Full instructions (SKILL.md)
Source of truth, from giuseppe-trisciuoglio/developer-kit.
name: unit-test-scheduled-async
description: Provides patterns for unit testing Spring @Scheduled and @Async methods using JUnit 5, CompletableFuture, Awaitility, and Mockito. Covers mocking task execution and timing, verifying execution counts, testing cron expressions, validating retry behavior, and simulating thread pool behavior. Use when testing background tasks, cron jobs, periodic execution, scheduled tasks, or thread pool behavior.
allowed-tools: Read, Write, Bash, Glob, Grep
Unit Testing @Scheduled and @Async Methods
Overview
Patterns 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.
When to Use
- Testing
@Scheduledmethod logic - Testing
@Asyncmethod behavior - Verifying
CompletableFutureresults - Testing async error handling
- Testing cron expression logic without waiting for actual scheduling
- Validating thread pool behavior and execution counts
- Testing background task logic in isolation
Instructions
- Call
@Asyncmethods directly — bypass Spring's async proxy; the annotation is irrelevant in unit tests - Mock dependencies with
@Mockand@InjectMocks(Mockito) - Wait for completion — use
CompletableFuture.get(timeout, unit)orawait().atMost(...).untilAsserted(...) - Call
@Scheduledmethods directly — do not wait for cron/fixedRate; the annotation is ignored in unit tests - Test exception paths — verify
ExecutionExceptionwrapping onCompletableFuture.get()
Validation checkpoints:
- After
CompletableFuture.get(), assert the returned value before verifying mock interactions - If
ExecutionExceptionis thrown, check.getCause()to identify the root exception - If Awaitility times out, increase
atMost()duration or reducepollInterval()until the condition is reachable - After multiple task invocations, assert execution counts before
verify()calls
Examples
Key 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.
Best Practices
- Always set a timeout on
CompletableFuture.get()to prevent hanging tests - Mock all dependencies — never call real external services in unit tests
- Use Awaitility only for race conditions; prefer direct calls for simple async methods
- Test
@Scheduledlogic directly — the annotation is ignored in unit tests - Assert values before verifying mock interactions; verify after async completion
Common Pitfalls
- Relying on Spring's async executor instead of calling methods directly
- Missing timeout on
CompletableFuture.get() - Forgetting to test exception propagation in async methods
- Not mocking dependencies that async methods invoke internally
- Waiting for actual cron/fixedRate timing instead of testing logic in isolation
Constraints and Warnings
@Asyncself-invocation: calling@Asyncfrom another method in the same class executes synchronously — the Spring proxy is bypassed- Thread pool ordering:
ThreadPoolTaskSchedulerdoes not guarantee execution order - CompletableFuture chaining: exceptions in intermediate stages can be silently lost — test each stage
- Awaitility timeout: always set a reasonable
atMost(); infinite waits hang the test suite - No actual scheduling:
@Scheduledis ignored in unit tests — call methods directly
References
- Spring
@AsyncDocumentation - Spring
@ScheduledDocumentation - Awaitility Testing Library
- CompletableFuture API
- Code examples:
references/examples.md
Related skills
More from giuseppe-trisciuoglio/developer-kit and the wider catalog.

unit-test-security-authorization
Unit test Spring Security authorization with @PreAuthorize, @Secured, and role-based access control patterns.

unit-test-service-layer
Unit test service layer with Mockito: mock dependencies, verify interactions, test business logic in isolation.

unit-test-utility-methods
Test patterns for utility classes, static methods, and pure functions with edge case coverage.

unit-test-wiremock-rest-api
Unit test REST API integrations with WireMock stubs, request verification, and error simulation.

wiremock-standalone-docker
Provides patterns and configurations for running WireMock as a standalone Docker container. Generates mock HTTP endpoints, creates stub mappings for testing, validates integration scenarios, and simulates error conditions. Use when you need to mock APIs, create a mock server, stub external services, simulate third-party APIs, or fake API responses for integration testing.

zod-validation-utilities
Creates reusable Zod v4 schemas, validates API payloads, forms, and configuration input, transforms and coerces data safely, and handles validation errors with strong type inference for TypeScript applications. Use when designing validation layers, parsing `z.string()`, `z.object()`, or `z.email()` schemas, or implementing runtime type-safe data validation.