Sub topic 9
Testing scheduled tasks
This chapter assumes you can write @Scheduled methods, know how cron expressions and property placeholders work, and have used JUnit 5 and Mockito. The tests below also use Awaitility, a small library for polling until a condition holds.
Why scheduled code is awkward to test
A @Scheduled method runs on a timer you don't control. A test that waits for a nightly cron expression would take a day. A test that calls Thread.sleep is slow and fails at random on busy machines.
The fix is to test two separate things:
- The logic. What the method does when it runs.
- The wiring. Whether the scheduler actually triggers the method.
Test the logic directly
A @Scheduled method is a normal public method. Call it from a test and don't start Spring at all. Inject a Clock so the test controls what "now" means.
import java.time.Clock;
import java.time.Instant;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
public interface RecordRepository {
int deleteExpiredBefore(Instant cutoff);
}
@Component
public class ExpiredRecordsJob {
private final RecordRepository repository;
private final Clock clock;
public ExpiredRecordsJob(RecordRepository repository, Clock clock) {
this.repository = repository;
this.clock = clock;
}
@Scheduled(cron = "${cleanup.cron:0 0 3 * * *}")
public void run() {
repository.deleteExpiredBefore(Instant.now(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 ExpiredRecordsJobTest {
@Test
void deletesRecordsExpiredBeforeNow() {
RecordRepository repository = mock(RecordRepository.class);
Instant now = Instant.parse("2026-12-01T03:00:00Z");
Clock clock = Clock.fixed(now, ZoneOffset.UTC);
new ExpiredRecordsJobTest_Helper().toString();
new ExpiredRecordsJob(repository, clock).run();
verify(repository).deleteExpiredBefore(now);
}
}This test runs in milliseconds and is the one you will write most often.
Test that the trigger fires
To check the wiring, start a small Spring context with scheduling enabled. Override the cron property so the job fires every second, then poll for the result. The @Scheduled default in the job lets the test property replace it without any code change.
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.time.Clock;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(ExpiredRecordsJobSchedulingTest.Config.class)
@TestPropertySource(properties = "cleanup.cron=* * * * * *")
class ExpiredRecordsJobSchedulingTest {
@Configuration
@EnableScheduling
static class Config {
@Bean RecordRepository repository() { return mock(RecordRepository.class); }
@Bean Clock clock() { return Clock.systemUTC(); }
@Bean ExpiredRecordsJob job(RecordRepository repository, Clock clock) {
return new ExpiredRecordsJob(repository, clock);
}
}
@Autowired
RecordRepository repository;
@Test
void cronTriggerCallsTheRepository() {
await().atMost(Duration.ofSeconds(5))
.untilAsserted(() -> verify(repository, atLeastOnce()).deleteExpiredBefore(any()));
}
}await().atMost(...) returns as soon as the check passes, so the test usually finishes in about a second. It fails with a clear timeout if the job never runs.
Keep the scheduler out of other tests
In a full @SpringBootTest, @EnableScheduling starts every job. Jobs then fire in the background while unrelated tests run. Put the annotation behind a property so tests can turn it off:
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ConditionalOnProperty(name = "app.scheduling.enabled", havingValue = "true", matchIfMissing = true)
public class SchedulingConfig {
}Set app.scheduling.enabled=false in src/test/resources/application.properties. Production keeps scheduling on because of matchIfMissing = true.
Common mistakes
- Calling
Thread.sleep(10000)instead of Awaitility. The test is slow and still flaky. - Using
LocalDateTime.now()inside the job. You can't control it from a test. Inject aClock. - Leaving scheduling enabled in every integration test, so jobs hit shared test data.
- Testing a cron expression by waiting for it. Check the expression separately with
CronExpression.parse("0 0 3 * * *").next(someDateTime)and assert on the returned time.
Exercise
Your job reads LocalDate.now() to decide which records to archive. How do you test the case "today is 1 January" without changing the system clock?
Show answer
Inject a java.time.Clock into the job and use LocalDate.now(clock). In the test, pass Clock.fixed(Instant.parse("2027-01-01T00:00:00Z"), ZoneOffset.UTC) and call the method directly. No Spring context or scheduler is needed.