有没有办法在Flutter测试中伪造DateTime.now()? [英] Is there a way to fake DateTime.now() in a Flutter test?

查看:42
本文介绍了有没有办法在Flutter测试中伪造DateTime.now()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将时间传递给我的窗口小部件,但是应该让我的窗口小部件本身实例化时间,而不是从父窗口小部件接收DateTime.

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.

推荐答案

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"); .无需使用第三方库.

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.

这篇关于有没有办法在Flutter测试中伪造DateTime.now()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆