【问题标题】:How to test if two durations are approximately equal in Dart如何在 Dart 中测试两个持续时间是否大致相等
【发布时间】:2021-06-24 06:48:52
【问题描述】:

我正在尝试测试两个持续时间的相等性。基本上问题归结为:

test('times are approximately equal', () {
  final expected = DateTime.now();
  final actual = DateTime.now();
  expect(actual, equals(expected));
});

此测试失败,因为时间略有不同:

Expected: DateTime:<2021-06-24 14:37:31.946196>  
  Actual: DateTime:<2021-06-24 14:37:31.946197>

只要持续时间彼此相差不到一秒,对我来说就足够接近了。我该如何测试?

我找到了答案,所以我在下面添加它。

【问题讨论】:

    标签: dart testing duration


    【解决方案1】:

    您可以将持续时间转换为毫秒,然后使用 closeTo 匹配器。

    test('times are approximately equal', () {
      final expected = DateTime.now();
      final actual = DateTime.now();
      expect(actual.millisecond, closeTo(expected.millisecond, 1000));
    });
    

    1000 是增量。这意味着只要预期的持续时间在实际持续时间的 1000 毫秒内,那么测试就会通过。

    感谢this answer 为我指明了正确的方向。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多