NUnit C# how to assert time (timestamp)

By: Slav Kurochkin

In my current project, for the API testing we need get token expiration date and make sure it is right? But what does it mean right?
Well, first that it is right format, second that it is in future.

Here is the solution for the time assertion in NUnit C#:

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); 
View Comments

Leave a Comment

Use markdown or basic HTML and be nice.