When we write tests – unit, integration, UI, etc. we often need to assert DateTime objects. However, the framework’s built-in methods not always can help us. If you compare your expected DateTime with the real one, they usually won’t be equal because of the seconds, milliseconds, etc. Because of that we need a better way to assert DateTimes with some delta.

For example if you want to compare:

2014.10.10 20:20:19 and 2014.10.10 20:20:20

These DateTimes are almost equal to a 1-second difference. In most cases, 1 seconds is not a problem. So you need an assert method that can be configured to ignore the 1-second discrepancy.

How to Assert DateTime in NUnit

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

So you don’t need to write a logic to test DateTimes.

How to Assert DateTime in MSTest

You will need an enum and a static class. The enum will hold the delta DateTime types- Seconds, Minutes, etc.

Next use the below class to assert DateTimes with particular delta count.

The private method GetTimeSpanDeltaByType is used to calculate the total seconds based on the Delta Type.

In order the primary Assert method to work in all cases(expectedDate > actualDate or expectedDate < actualDate) we use Math.Abs when we calculate the total of the actual and expected DateTimes subtraction.

The usage is pretty straightforward:

Improved Version

Almost half year after initial publication, I created an even better implementation of the class. Credits go to my great readers in CodeProject. Thank you!

This version usage is more expressive and gives the freedom to use any Delta: