How to test code that uses DateTime.now in Flutter?
If you use the clock package for code depending on DateTime.now()
you can easily mock it.
I don't think there is a good way without a wrapper around DateTime.now()
licke the clock
package provides.
As mentioned here: https://stackoverflow.com/a/63073876/2235274 implement extension on DateTime.
extension CustomizableDateTime on DateTime { static DateTime _customTime; static DateTime get current { return _customTime ?? DateTime.now(); } static set customTime(DateTime customTime) { _customTime = customTime; }}
Then just use CustomizableDateTime.current
in the production code. You can modify the returned value in tests like that: CustomizableDateTime.customTime = DateTime.parse("1969-07-20 20:18:04");
. There is no need to use third party libraries.
As Günther 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.