Skip to main content
skill CX Codex

unit-test-scheduled-async — Claude Code skill for @Scheduled

A skill with ready patterns for unit testing Spring @Scheduled and @Async methods: JUnit 5, CompletableFuture, Awaitility, Mockito.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill unit-test-scheduled-async -a claude-code
Open on GitHub

What unit-test-scheduled-async does

The skill covers unit testing Spring background tasks without waiting for real scheduler intervals. @Async and @Scheduled methods get called directly, since both annotations are ignored in unit tests and Spring's proxy is bypassed anyway. You check the CompletableFuture result with get(timeout, unit) and swap dependencies with @Mock and @InjectMocks.

Inside are five steps, from calling the method straight through to verifying exception paths, plus validation checkpoints and code samples: waiting for completion, race conditions on shared mutable state via Awaitility, execution counts, error handling in async chains. Full examples with Maven and Gradle dependencies live in references/examples.md.

The trap worth knowing: self-invocation. Call an @Async method from another method in the same class and the Spring proxy never fires, so the code runs synchronously. Your test passes, production breaks. ThreadPoolTaskScheduler also gives no ordering guarantee, so asserting task sequence is pointless. Always set a timeout in atMost() and in get() — a hung test takes the whole suite with it.

What it helps with

  • test @Scheduled logic without waiting for the cron to fire
  • assert a CompletableFuture result from an @Async method with a timeout
  • wait for a race condition to settle via Awaitility
  • count how many times a background task ran
  • verify that an exception inside an async method wraps into ExecutionException

Example prompts for the agent

  • write a unit test for the @Async sendEmailAsync method and assert its CompletableFuture
  • test the @Scheduled refreshCache method with a mocked repository
  • help me test the race condition in BackgroundWorker with Awaitility

How to install unit-test-scheduled-async

1Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill unit-test-scheduled-async -a claude-code

2Manually: put the files in place

~/.claude/skills/unit-test-scheduled-async/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/unit-test-scheduled-async/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about unit-test-scheduled-async

How do I install unit-test-scheduled-async in Claude?

Run npx skills add giuseppe-trisciuoglio/developer-kit --skill unit-test-scheduled-async -a claude-code. The skill lands in ~/.claude/skills/unit-test-scheduled-async/SKILL.md.

What does unit-test-scheduled-async do?

It provides unit test patterns for Spring @Scheduled and @Async methods: direct invocation, waiting on CompletableFuture, Awaitility for race conditions, Mockito for dependencies.

Why does my @Async method run synchronously in the test?

Self-invocation from another method in the same class bypasses the Spring proxy, so the call runs synchronously. In unit tests that is expected — you call the methods directly.

Source text

SKILL.md · MIT
---
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 `@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 reachable
- After multiple task invocations, assert execution counts before `verify()` calls

## Examples

Key patterns — complete examples in `references/examples.md`:

```java
// @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("[email protected]").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 `@Scheduled` **logic** 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

- **`@Async` self-invocation**: calling `@Async` from another method in the same class executes synchronously — the Spring proxy is bypassed
- **Thread pool ordering**: `ThreadPoolTaskScheduler` does 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**: `@Scheduled` is ignored in unit tests — call methods directly

## References

- [Spring `@Async` Documentation](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Async.html)
- [Spring `@Scheduled` Documentation](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html)
- [Awaitility Testing Library](https://github.com/awaitility/awaitility)
- [CompletableFuture API](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html)
- Code examples: `references/examples.md`

© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar skills

Everything for Testing and QA →

From the same set93

qdrant Provides integration patterns for the Qdrant vector database in Java and Spring Boot with LangChain4j. Helps build semantic search and vector stores for RAG. CX Codex +1 3,700installs unit-test-mapper-converter A skill for unit-testing MapStruct mappers and converters: field mapping, null handling, nested objects and round-trip conversion. CX Codex +1 3,700installs unit-test-exception-handler Patterns for unit testing @ExceptionHandler and @ControllerAdvice in Spring Boot: status codes, JSON error bodies and field-level validation errors. CX Codex +1 3,700installs rag Guides the creation of Retrieval-Augmented Generation pipelines, covering document chunking, embedding generation, vector database selection, and retrieval. CX Codex +1 3,700installs unit-test-utility-methods Writes unit tests for utility classes and static methods, covering nulls, empty input, boundaries and floating-point precision. CX Codex +1 3,700installs nextjs-data-fetching Provides Next.js App Router data fetching patterns, covering Server Components, ISR caching strategies, and SWR or React Query client integration. CX Codex +1 3,700installs langchain4j-rag-implementation-patterns A coding-agent skill that scaffolds LangChain4j RAG pipelines: document ingestion, embedding stores, vector search and knowledge-base answers. CX Codex +1 3,700installs nx-monorepo A skill that walks the agent through Nx: workspace setup, generators, affected commands, Module Federation and CI. CX Codex +1 3,700installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor