How to test code that uses DateTime.now in Flutter?

As Günter said, the clock package, maintained by the Dart team, provides a very neat way to achieve this.

Normal usage:

import 'package:clock/clock.dart';

void main() {
  // prints current date and time
  print(clock.now());
}

Overriding the current time:

import 'package:clock/clock.dart';

void main() {
  withClock(
    Clock.fixed(DateTime(2000)),
    () {
      // always prints 2000-01-01 00:00:00.
      print(clock.now());
    },
  );
}

I wrote about this in more detail on my blog.

For widget tests, you need to wrap pumpWidget, pump and expect in the withClock callback.

Leave a Comment