问题
I can pass in a time to my widget, but my widget is supposed to be instantiating the time in itself, not receiving a DateTime from a parent widget.
回答1:
extension CustomizableDateTime on DateTime {
static DateTime customTime;
static DateTime get current {
if (customTime != null)
return customTime;
else
return DateTime.now();
}
}
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.
回答2:
The clock package: https://pub.dartlang.org/documentation/clock/latest/clock/clock-library.html lets you inject a fake clock into the test.
来源:https://stackoverflow.com/questions/53674027/is-there-a-way-to-fake-datetime-now-in-a-flutter-test