C#、NUnit:是否可以测试一个 DateTime 是否与另一个 DateTime 非常接近,但不一定相等?
假设我有这个测试:
[Test]
public void SomeTest()
{
var message = new Thing("foobar");
Assert.That(thing.Created, Is.EqualTo(DateTime.Now));
}
例如,这可能会导致 Thing 的构造函数失败,需要一些时间。是否有某种 NUnit 构造允许我指定 Created
时间不必完全等于 DateTime.Now
,例如只要在一秒之内?
是的,我知道构造函数不应该花费太多时间,但只是作为一个例子:p
Say I have this test:
[Test]
public void SomeTest()
{
var message = new Thing("foobar");
Assert.That(thing.Created, Is.EqualTo(DateTime.Now));
}
This could for example fail the constructor of Thing took a bit of time. Is there some sort of NUnit construct that would allow me to specify that the Created
time don't have to be exactly equal to DateTime.Now
, as long as it for example is within one second of it?
And yes I know constructors are not supposed to take much time, but just as an example :p
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我还没有尝试过,但根据文档看起来这应该可行:
我不能说我通常是约束系统的粉丝 - 我是一个 Assert.AreEqual 粉丝 - 但这个特定的构造相当简洁。
(作为一个原则,我应该指出,您最好将某种“时钟”接口作为依赖项传递,然后就不会出现任何不准确的情况。您可以在测试中伪造它,并使用用于生产的系统时钟。)
I haven't tried it, but according to the docs it looks like this should work:
I can't say I'm normally much of a fan of the constraints system - I'm an
Assert.AreEqual
fan - but that particular construct is rather neat.(As a point of principle I should remark that you'd be best off passing some sort of "clock" interface in as a dependency, and then you wouldn't have any inaccuracy. You could fake it for the tests, and use the system clock for production.)
检查 TimeSpan 对象 - 使用 TimeSpan 比较两个日期并检查值是否在阈值内。
Check out the TimeSpan object - compare both dates using TimeSpan and check to see if the values are within your threshold.
您需要从定义“非常接近”开始。如果“非常接近”指的是几百个刻度,那么您可以这样做:
然后只要您的日期在 200 个刻度以内,您的测试就会通过。
You'd need to start out by defining "very close". If by "very close" you mean a few hundred ticks then you could do this:
Then whenever you've got dates within 200 ticks your test passes.
您可以检查减去它们并检查时间跨度。
为您提供总秒数。
You could check subtract them and check the timespan.
Gives you the totalseconds.
您始终可以减去 DateTime 变量并得到 TimeSpan。有了时间跨度,你就可以做任何你想做的事情。
You can always subtract DateTime variables and you get TimeSpan. With Time span you can do whatever you want.