NUnit Assert.AreEqual DateTime Tolerances

Jim*_*m B 56 c# nunit .net-3.5

我想知道是否有人找到了一个很好的解决方案:

在我们的单元测试中; 我们通常Assert.AreEqual()用来验证我们的结果.一切都很好; 直到我们开始尝试在DateTime属性上使用它.

尽管时间非常相似,但有时它们会以毫秒为单位,这会导致测试失败.在我们的申请中; 只要它们准确到第二; 这对我们来说已经足够了.

在这种情况下,有没有人找到以某种方式实施公差的好方法?通常我们的解决方法是将其拆分为两个单独的语句; 一个检查.ToShortDateString(),另一个检查.ToShortTimeString(),但在我看来这看起来很草率.

Raj*_*esh 87

使用Assert.ThatIs.Equal约束而不是Assert.AreEqual.以下是Nunit网站本身的代码示例

DateTime now = DateTime.Now;
DateTime later = now + TimeSpan.FromHours(1.0);

Assert.That(now, Is.EqualTo(now) );
Assert.That(later, Is.EqualTo(now).Within(TimeSpan.FromHours(3.0)));
Assert.That(later, Is.EqualTo(now).Within(3).Hours);
Run Code Online (Sandbox Code Playgroud)

  • 为什么使用“Assert.That”而不是“Assert.AreEqual”?你能给一些解释吗? (2认同)

SwD*_*n81 81

您可以使用以下内容检查公差:

Debug.Assert((date1 - date2) < TimeSpan.FromSeconds(1));
Run Code Online (Sandbox Code Playgroud)

如果您不确定哪个日期更新,请使用

Debug.Assert(Math.Abs((date1 - date2).TotalSeconds) < 1)
Run Code Online (Sandbox Code Playgroud)

NUnit还使用Within关键字为此添加了内置支持

DateTime now = DateTime.Now;
DateTime later = now + TimeSpan.FromHours(1.0);

Assert.That(later, Is.EqualTo(now).Within(TimeSpan.FromHours(3.0)));
Assert.That(later, Is.EqualTo(now).Within(3).Hours);
Run Code Online (Sandbox Code Playgroud)

  • 如果date2比date1大一秒以上,则会失败.应该检查差异的总秒数的绝对值.例如`Debug.Assert(Math.Abs​​((date1 - date2).TotalSeconds)<1)` (4认同)
  • NUnit内置了对此的支持,请参阅下面的答案http://stackoverflow.com/questions/3577856/nunit-assert-areequal-datetime-tolerances/7601507#7601507 (2认同)

Nat*_*nst 10

要正确检查任何2个任意日期是否等于1秒容差,以下是正确的解决方案:

Debug.Assert(Math.Abs((date1 - date2).TotalSeconds) < 1)
Run Code Online (Sandbox Code Playgroud)

我想我会添加为一个解决方案,因为当接受的解决方案是不正确date2大于date1超过一秒钟,按照我给@ SwDevMan81注释的解决方案尚未更新.