开发者

C#, NUnit: Is it possible to test that a DateTime is very close, but not necessarily equal, to another?

Say I have this test:

[Test]
public void S开发者_运维问答omeTest()
{
    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


I haven't tried it, but according to the docs it looks like this should work:

Assert.That(thing.Created, Is.EqualTo(DateTime.Now).Within(1).Minutes);

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.)


Check out the TimeSpan object - compare both dates using TimeSpan and check to see if the values are within your threshold.

TimeSpan span = thing.Created - DateTime.Now;
if(span.TotalSeconds <= 1)
   [..]


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:

Assert.That(200, Is.LessThanOrEqualTo(DateTime.Now.Ticks - thing.Created.Ticks));

Then whenever you've got dates within 200 ticks your test passes.


You could check subtract them and check the timespan.

        DateTime.Now.Subtract(thing.Created).TotalSeconds

Gives you the totalseconds.


You can always subtract DateTime variables and you get TimeSpan. With Time span you can do whatever you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜