Testing and time

Scheduled methods run in springBootTest too. To keep tests deterministic, switch scheduling off and call the methods directly, or let the test move time with fake_async or a Flutter widget test. The scheduler reads the time of package:clock, which those tools fake.

Why

A test that waits five real minutes for a schedule is useless, and one that races a timer is flaky. Calling the method directly tests what it does; moving fake time tests when it runs.

Example

import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';

import 'spring_gen/main.test.spring.dart';

void main() {
  final app = springBootTest(
    springApplication,
    properties: {'spring.task.scheduling.enabled': false},
  );

  test('refresh', () => app.getBean<Reports>().refreshCache());
}
// A schedule run on fake time: 5 minutes pass in an instant.
fakeAsync((async) {
  var runs = 0;
  final scheduler = TimerTaskScheduler();
  scheduler.scheduleAtFixedRate(() => runs++, const Duration(minutes: 1));
  async.elapse(const Duration(minutes: 5));
  expect(runs, greaterThanOrEqualTo(5)); // a run at the start, then one per minute
});

Moving time

Flutter widget tests (tester.pump) and fake_async fake the timers and the current time of package:clock, which the scheduler reads by default:

With timers of its own, a test passes the current time and the timers of its fake clock: TimerTaskScheduler(now: ..., createTimer: ...), registered through BeanOverride. ScheduledAnnotationBeanPostProcessor.scheduledTasks lists what is scheduled.

How the scheduler reads time

fixedRate and fixedDelay never read the wall clock. As Spring's executor counts on a monotonic clock, each task keeps a timeline of its own that its timers move:

So setting the wall clock (by hand, or a time server) moves none of their runs, and neither does a clock that stands still, runs slow or fast, or jumps while real timers wait. Two limits, both under a clock of its own:

A cron or scheduleAt time is a wall clock time: the scheduler computes the wait from the wall clock, and the timers wait it. When the wall clock is set back during the wait, the run comes early by the wall clock, once; the next time is planned from the wall clock again. A wait longer than a day is made of timers of at most a day, so it ends within a day of the wall clock passing its time.

Hot reload

Tasks belong to the context: a hot-reload restart closes it, which cancels every task, and the new context schedules the methods of the new code.

In Spring (Java)

@SpringBootTest(properties = "spring.task.scheduling.enabled=false")
class ReportsTest { ... }

Spring tests usually use Awaitility or call the method directly; here fake time moves the scheduler too.

See also