Video in progress

Strong Middle 🧪 Testing

How do you test a job that runs with @Scheduled?

I separate the scheduling from the work itself: I test the job logic by calling the method directly, test the cron expression separately with CronExpression, and switch the scheduler off in the test profile, otherwise it fires on its own between tests and changes data.

📖 Answer

A bad approach is to set the cron to every second and wait with Thread.sleep(3000) to see "did the job run". It's slow, flaky, and still doesn't check the cron itself.

I make the job thin: the @Scheduled method only calls a service.

@Component
class ExpireSubscriptionsJob {
    private final SubscriptionService service;
    ExpireSubscriptionsJob(SubscriptionService service) { this.service = service; }

    @Scheduled(cron = "${jobs.expire.cron:0 5 0 * * *}", zone = "Asia/Tashkent")
    void run() { service.expireOverdue(); }
}

Then three kinds of test:

// 1. Logic: with a Clock, without the scheduler
@Test
void expiresOnlyOverdue() {
    var clock = Clock.fixed(Instant.parse("2026-03-02T00:00:00Z"), ZoneOffset.UTC);
    // ... check the result of service.expireOverdue()
}

// 2. The cron expression: when it runs
@Test
void runsFiveMinutesAfterMidnight() {
    var next = CronExpression.parse("0 5 0 * * *").next(LocalDateTime.of(2026, 3, 1, 23, 0));
    assertThat(next).isEqualTo(LocalDateTime.of(2026, 3, 2, 0, 5));
}

// 3. Is the job registered: in the Spring context
@Autowired ScheduledTaskHolder holder;
@Test
void jobIsRegistered() {
    assertThat(holder.getScheduledTasks()).extracting(t -> t.getTask().toString())
        .anyMatch(s -> s.contains("ExpireSubscriptionsJob.run"));
}

To switch the scheduler off in the test profile, I move @EnableScheduling into a separate configuration, put @ConditionalOnProperty(name = "app.scheduling.enabled", matchIfMissing = true) on it, and set it to false in tests. That way the job doesn't unexpectedly fire between integration tests.

In a service that runs on several instances, you should also test that the job doesn't run twice (ShedLock or a database lock): I call run() from two threads at the same time and check that the result happened once.