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

cdatetimenunitunit testing

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

Best Answer

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