views:

198

answers:

5

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

+9  A: 

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

Jon Skeet
ooh, nice :D These constraints just keep surprising me... Is there a nice guide that walks through all of these with some good usage examples? (Other than the manual, which is pretty good too)
Svish
Can't say I know much about them myself. I just looked up the docs when I saw your question, hoping there'd be a nice simple solution. I was expecting to have to take the ticks and form an approximation that way - I was very pleased when I saw the "minutes" property.
Jon Skeet
Yes. These constraints are better for verify precision in numbers, for example Assert.That(actualResult, Is.EqualTo(expectedResult).Within(0.00000001).Percent);
RichardOD
A: 

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

kubal5003
+1  A: 

You could check subtract them and check the timespan.

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

Gives you the totalseconds.

JoshBerke
+1  A: 

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)
   [..]
Polatrite
You want to use TotalSeconds Seconds get you the seconds component so if the span is 61 seconds total, this would pass your check.
JoshBerke
Thanks for the reminder - I remember making this mistake while working with TimeSpan quite a while back. :)
Polatrite
Yup, been there done that :p
Svish
(The Seconds instead of TotalSeconds bug that is...)
Svish
+2  A: 

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.

_rusty
... so long as it doesn't decide to create it in the future, of course.
Jon Skeet