首页 > 解决方案 > Is there a way to fake DateTime.now() in a Flutter test?

问题描述

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.

标签: testingtimeflutter

解决方案


extension CustomizableDateTime on DateTime {
  static DateTime customTime;
  static DateTime get current {
    if (customTime != null)
      return customTime;
    else
      return DateTime.now();
  }
}

只需CustomizableDateTime.current在生产代码中使用。您可以像这样在测试中修改返回值:CustomizableDateTime.customTime = DateTime.parse("1969-07-20 20:18:04");. 无需使用第三方库。


推荐阅读