Is there a way to fake DateTime.now() in a Flutter test?

夙愿已清 提交于 2020-12-15 06:57:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!