unit-test-scheduled-async

Solid

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.

Testing & QA 278 stars 32 forks Updated 5 days ago MIT

Install

View on GitHub

Quality Score: 91/100

Stars 20%
81
Recency 20%
100
Frontmatter 20%
70
Documentation 15%
100
Issue Health 10%
50
License 10%
100
Description 5%
100

Skill Content

# 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 `@Scheduled` method logic - Testing `@Async` method behavior - Verifying `CompletableFuture` results - 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 1. **Call `@Async` methods directly** — bypass Spring's async proxy; the annotation is irrelevant in unit tests 2. **Mock dependencies** with `@Mock` and `@InjectMocks` (Mockito) 3. **Wait for completion** — use `CompletableFuture.get(timeout, unit)` or `await().atMost(...).untilAsserted(...)` 4. **Call `@Scheduled` methods directly** — do not wait for cron/fixedRate; the annotation is ignored in unit tests 5. **Test exception paths** — verify `ExecutionException` wrapping on `CompletableFuture.get()` **Validation checkpoints:** - After `CompletableFuture.get()`, assert the returned value before verifying mock interactions - If `ExecutionException` is thrown, check `.getCause()` to identify the root exception - If Awaitility times out, increase `atMost()` duration or reduce `pollInterval()` until the condition is reach...

Details

Author
giuseppe-trisciuoglio
Repository
giuseppe-trisciuoglio/developer-kit
Created
7 months ago
Last Updated
5 days ago
Language
Python
License
MIT

Integrates with

Similar Skills

Semantically similar based on skill content — not just same category