NUnit Assert.AreEqual 日期时间容差
我想知道是否有人找到了一个好的解决方案:
在我们的单元测试中;我们通常使用 Assert.AreEqual()
来验证我们的结果。一切都很好;直到我们开始尝试在 DateTime 属性上使用它。
尽管时间非常相似,但有时会相差几毫秒,这会导致测试失败。在我们的应用程序中;只要精确到秒;这对我们来说已经足够了。
在这种情况下,有人找到了以某种方式实现容差的好方法吗?通常我们的解决方法是将其分成 2 个单独的语句;一个检查 .ToShortDateString()
,另一个检查 .ToShortTimeString()
,但在我看来这看起来很草率。
I'm wondering if anybody's found a good solution to this:
In our unit tests; we commonly use Assert.AreEqual()
to validate our results. All is well and good; until we start trying to use this on DateTime properties.
Although the times are very similar, sometimes they are off by milliseconds, which causes the tests to fail. In our application; as long as they're accurate to the second; that's good enough for us.
Has anybody found a good way to somehow implement tolerances in this case? Typically our workaround is to split it into 2 separate statements; one which checks the .ToShortDateString()
, and another that checks .ToShortTimeString()
, but this looks sloppy in my opinion.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 Assert.That 和 Is.Equal 约束而不是 Assert.AreEqual。以下是 Nunit 网站本身的代码示例
Use Assert.That and Is.Equal constraint instead of Assert.AreEqual. Below is a code sample from the Nunit website itself
您可以使用以下方法检查容差:
如果您不确定哪个日期较新,请使用
NUnit 还使用
Within
关键字You can check tolerances with something like:
If you are unsure which date is newer, use
NUnit has also added built in support for this using the
Within
keyword要正确检查任意 2 个任意日期是否等于 1 秒容差内,以下是正确的解决方案:
我想我会将其添加为解决方案,因为当
date2
时,接受的解决方案不正确比date1
大一秒以上,并且根据我对 @SwDevMan81 的评论,该解决方案尚未更新。To correctly check if any 2 arbitrary dates are equals to within a 1 second tolerance, the following is a correct solution:
I figured I'd add this as a solution since the accepted solution was incorrect when
date2
is larger thandate1
by more than a second, and the solution has not been updated following my comment to @SwDevMan81.