Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit Assert.AreEqual DateTime Tolerances

Tags:

c#

.net-3.5

nunit

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.

like image 987
Jim B Avatar asked Aug 26 '10 17:08

Jim B


3 Answers

Use Assert.That and Is.Equal constraint instead of Assert.AreEqual. Below is a code sample from the Nunit website itself

DateTime now = DateTime.Now;
DateTime later = now + TimeSpan.FromHours(1.0);

Assert.That(now, Is.EqualTo(now) );
Assert.That(later, Is.EqualTo(now).Within(TimeSpan.FromHours(3.0)));
Assert.That(later, Is.EqualTo(now).Within(3).Hours);
like image 164
Rajeesh Avatar answered Nov 09 '22 23:11

Rajeesh


You can check tolerances with something like:

Debug.Assert((date1 - date2) < TimeSpan.FromSeconds(1));

If you are unsure which date is newer, use

Debug.Assert(Math.Abs((date1 - date2).TotalSeconds) < 1)

NUnit has also added built in support for this using the Within keyword

DateTime now = DateTime.Now;
DateTime later = now + TimeSpan.FromHours(1.0);

Assert.That(later, Is.EqualTo(now).Within(TimeSpan.FromHours(3.0)));
Assert.That(later, Is.EqualTo(now).Within(3).Hours);
like image 35
SwDevMan81 Avatar answered Nov 10 '22 01:11

SwDevMan81


To correctly check if any 2 arbitrary dates are equals to within a 1 second tolerance, the following is a correct solution:

Debug.Assert(Math.Abs((date1 - date2).TotalSeconds) < 1)

I figured I'd add this as a solution since the accepted solution was incorrect when date2 is larger than date1 by more than a second, and the solution has not been updated following my comment to @SwDevMan81.

like image 10
Nathan Ernst Avatar answered Nov 10 '22 01:11

Nathan Ernst