Sub topic 9
Testing scheduled tasks
Scheduled methods are hard to test because they run on a timer, on another thread, and often at a time of day you can't wait for. This chapter shows how to split a scheduled task into parts you can test quickly and reliably. It also shows how to check the schedule itself, and how to run a real scheduler in a test without making the suite slow or flaky.
It assumes you can write JUnit 5 tests with Mockito, that you know @SpringBootTest, and that you have read the earlier chapters on @Scheduled, cron expressions and property placeholders.
What there is to test
A scheduled task has three separate parts, and each needs a different kind of test.
- The work. What the method does when it runs: deleting rows, sending a report, calling a service.
- The trigger. The cron expression, rate or delay, and the time zone that decide when it runs.
- The wiring. Whether Spring actually registers the method and calls it repeatedly.
Most of your tests should cover the work. They are plain unit tests with no Spring context and no waiting. Trigger tests are also cheap. Wiring tests need a running context and a real scheduler, so write only a few.
Test the work by calling the method
A @Scheduled method is an ordinary public method. Nothing stops a test from calling it. The only requirement is that the method does its job through collaborators you can replace.
The job below deletes records older than 30 days. It takes a Clock so that "now" is controllable.
public interface ExpiredRecordRepository {
void deleteOlderThan(Instant cutoff);
}
@Component
public class CleanupJob {
private final ExpiredRecordRepository repository;
private final Clock clock;
public CleanupJob(ExpiredRecordRepository repository, Clock clock) {
this.repository = repository;
this.clock = clock;
}
@Scheduled(cron = "${cleanup.cron:0 0 3 * * *}")
public void cleanup() {
repository.deleteOlderThan(Instant.now(clock).minus(Duration.ofDays(30)));
}
}Spring Boot does not provide a Clock bean by default. Declare one in a configuration class:
@Configuration
public class ClockConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
}The test creates the job directly with a mock repository and a fixed clock:
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import org.junit.jupiter.api.Test;
class CleanupJobTest {
private final ExpiredRecordRepository repository = mock(ExpiredRecordRepository.class);
private final Clock clock =
Clock.fixed(Instant.parse("2026-12-01T03:00:00Z"), ZoneOffset.UTC);
@Test
void deletesRecordsOlderThanThirtyDays() {
new CleanupJob(repository, clock).cleanup();
verify(repository).deleteOlderThan(Instant.parse("2026-11-01T03:00:00Z"));
}
}This test runs in milliseconds and gives the same result on every run. If the work is more than a few lines, move it into a service and keep the scheduled method as a one-line call. Then the job class is trivial and the service has its own tests.
Test the trigger with CronExpression
A typo in a cron string is only noticed when the task fails to run. Spring validates the expression at startup, so a malformed one fails the application context. A well-formed but wrong one, such as "3 a.m." written as the wrong field, passes validation.
CronExpression is the same class the scheduler uses. You can parse an expression in a test and ask when it fires next:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.jupiter.api.Test;
import org.springframework.scheduling.support.CronExpression;
class ReportScheduleTest {
private static final ZoneId BERLIN = ZoneId.of("Europe/Berlin");
@Test
void nightlyReportFiresAtTwoInTheMorningBerlinTime() {
CronExpression cron = CronExpression.parse("0 0 2 * * *");
ZonedDateTime from = ZonedDateTime.of(2026, 12, 1, 10, 0, 0, 0, BERLIN);
ZonedDateTime next = cron.next(from);
assertEquals(ZonedDateTime.of(2026, 12, 2, 2, 0, 0, 0, BERLIN), next);
}
}The time zone matters here. next works in the zone of the value you pass, so use a ZonedDateTime in the zone you set in @Scheduled(zone = ...). Passing a LocalDateTime ignores daylight saving rules entirely.
This test checks an expression you copy into the test. It does not read the string from the annotation, so it can drift from the code. To avoid that, put the expression in a constant and use it in both places:
public static final String NIGHTLY_CRON = "0 0 2 * * *";
@Scheduled(cron = NIGHTLY_CRON, zone = "Europe/Berlin")
public void nightlyReport() { /* ... */ }If the schedule comes from a property, test the property's default value the same way, or load the real application.yml value in a @SpringBootTest and parse it.
Test the wiring with a real scheduler
Sometimes you want proof that Spring finds the annotation, calls the method, and calls it again. This needs a Spring context and a short interval. Use fixedRateString with a property placeholder so the test can shorten it:
@Component
public class HeartbeatJob {
private final AtomicInteger runs = new AtomicInteger();
@Scheduled(fixedRateString = "${heartbeat.rate:PT1M}")
public void beat() {
runs.incrementAndGet();
}
public int runs() {
return runs.get();
}
}The default is one minute. The test overrides it to 50 milliseconds. A plain number in a ...String attribute is read as milliseconds.
import static org.awaitility.Awaitility.await;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(properties = "heartbeat.rate=50")
class HeartbeatJobIntegrationTest {
@Autowired
private HeartbeatJob job;
@Test
void schedulerCallsTheMethodRepeatedly() {
await().atMost(Duration.ofSeconds(2)).until(() -> job.runs() >= 3);
}
}Awaitility is a test library that polls a condition until it becomes true or a time limit passes. Add it as a test dependency:
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>The test passes as soon as three runs have happened, usually within about 150 ms, and fails only if two seconds pass without that. It does not wait a fixed time.
You can also check calls on a Mockito spy bean with verify(spy, timeout(2000).atLeast(3)).beat(). The spy annotation depends on your Spring Boot version: @SpyBean in older versions, and @MockitoSpyBean since Spring Framework 6.2 (Spring Boot 3.4), where @SpyBean is deprecated.
Keep the scheduler out of unrelated tests
By default, every @SpringBootTest starts the scheduler and runs your jobs. A nightly job that deletes data might fire in the middle of an unrelated integration test. Two techniques prevent this.
The first is to make @EnableScheduling conditional. Move it from the application class into its own configuration:
@Configuration
@EnableScheduling
@ConditionalOnProperty(
name = "app.scheduling.enabled",
havingValue = "true",
matchIfMissing = true)
public class SchedulingConfig {
}In production the property is missing, so scheduling is on. A test that does not want timers sets app.scheduling.enabled=false, for example in src/test/resources/application.properties. Tests that do want the scheduler, such as the heartbeat test above, override it back to true.
The second technique is to disable one trigger through its property. For cron, the special value - turns the task off. Scheduled.CRON_DISABLED holds this constant.
@SpringBootTest(properties = "cleanup.cron=-")
class SomeOtherIntegrationTest {
// CleanupJob is registered but never fires
}This works only for cron. A fixedDelayString or fixedRateString has no disabled value, so use the conditional configuration for those.
Summary of approaches
| Approach | What it proves | Speed | Flakiness risk |
|---|---|---|---|
| Call the method in a unit test | The work is correct | Milliseconds | None |
| `CronExpression.next` | The schedule fires when you expect | Milliseconds | None |
| `@SpringBootTest` with Awaitility | Spring registers and repeats the task | Seconds | Low if the timeout is generous |
| Disabled scheduling in other tests | Timers do not interfere | No cost | None |
Common mistakes
- Testing only through the scheduler. Every test then needs a context and a wait. Call the method directly whenever you are testing the work.
- Using the real clock. Code that calls
Instant.now()orLocalDate.now()gives different results at different times. Inject aClock. - Asserting the exact number of runs. Timer-driven counts vary with machine load. Assert "at least N".
- Forgetting the thread. The scheduled method runs on a scheduler thread, so state it changes must be visible to the test thread. Use
AtomicInteger,volatilefields or thread-safe collections. - Leaving the scheduler running between tests. Spring caches test contexts, so a running job can keep firing during later tests that share the context. Disable scheduling in those tests.
Exercise
A job uses @Scheduled(fixedDelayString = "${sync.delay:PT10M}"). You write a @SpringBootTest for a different feature and notice the job runs during it and changes data. Cron has a - value that disables a trigger. Why can't you use that here, and what two things could you do instead?
Show answer
Only cron supports the - value (Scheduled.CRON_DISABLED). A fixed delay or fixed rate has no disabled value, so sync.delay=- would fail to parse. You can set sync.delay to a very long duration such as PT24H for that test, or put @EnableScheduling in a configuration class guarded by @ConditionalOnProperty and set app.scheduling.enabled=false in the test. The conditional configuration is cleaner because it turns off all timers at once.
Exercise
Write the assertion line that checks CronExpression.parse("0 30 8 * * MON-FRI") fires next at 08:30 on Monday 2026-12-07 when asked from Friday 2026-12-04 at 09:00 UTC. Use ZonedDateTime and ZoneOffset.UTC.
Show answer
assertEquals(ZonedDateTime.of(2026, 12, 7, 8, 30, 0, 0, ZoneOffset.UTC), CronExpression.parse("0 30 8 MON-FRI").next(ZonedDateTime.of(2026, 12, 4, 9, 0, 0, 0, ZoneOffset.UTC))); The Friday 08:30 slot has already passed at 09:00, and the weekend is skipped, so the next fire is Monday.