Introduction
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 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;
So you don’t need to write your own logic to test DateTime
s.
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.
public enum DateTimeDeltaType
{
Days,
Minutes
}
Next, use the below class to assert DateTime
s with specific delta count.
public static class DateTimeAssert
{
public static void Validate(DateTime? expectedDate, _
DateTime? actualDate, DateTimeDeltaType deltaType, int count)
{
if (expectedDate == null && actualDate == null)
{
return;
}
else if (expectedDate == null)
{
throw new NullReferenceException("The expected date was null");
}
else if (actualDate == null)
{
throw new NullReferenceException("The actual date was null");
}
TimeSpan expectedDelta = GetTimeSpanDeltaByType(deltaType, count);
double totalSecondsDifference = Math.Abs(((DateTime)actualDate -
(DateTime)expectedDate).TotalSeconds);
if (totalSecondsDifference > expectedDelta.TotalSeconds)
{
throw new Exception(string.Format("Expected Date: {0},
Actual Date: {1} \nExpected Delta: {2}, Actual Delta in seconds- {3} (Delta Type: {4})",
expectedDate,
actualDate,
expectedDelta,
totalSecondsDifference,
deltaType));
}
}
private static TimeSpan GetTimeSpanDeltaByType(DateTimeDeltaType type, int count)
{
TimeSpan result = default(TimeSpan);
switch (type)
{
case DateTimeDeltaType.Days:
result = new TimeSpan(count, 0, 0, 0);
break;
case DateTimeDeltaType.Minutes:
result = new TimeSpan(0, count, 0);
break;
default: throw new NotImplementedException("The delta type is not implemented.");
}
return result;
}
}
The private
method GetTimeSpanDeltaByType
is used to calculate the total seconds based on the Delta Type.
In order for the main 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 DateTime
s subtraction.
The usage is pretty simple:
DateTimeAssert.Validate(
new DateTime(2014, 10, 10, 20, 22, 16),
new DateTime(2014, 10, 11, 20, 22, 16),
DateTimeDeltaType.Days,
1);
So Far in the C# Series
1. Implement Copy Paste C# Code
2. MSBuild TCP IP Logger C# Code
3. Windows Registry Read Write C# Code
4. Change .config File at Runtime C# Code
5. Generic Properties Validator C# Code
6. Reduced AutoMapper- Auto-Map Objects 180% Faster
7. 7 New Cool Features in C# 6.0
8. Types Of Code Coverage- Examples In C#
9. MSTest Rerun Failed Tests Through MSTest.exe Wrapper Application
10. Hints For Arranging Usings in Visual Studio Efficiently
11. 19 Must-Know Visual Studio Keyboard Shortcuts – Part 1
12. 19 Must-Know Visual Studio Keyboard Shortcuts – Part 2
13. Specify Assembly References Based On Build Configuration in Visual Studio
14. Top 15 Underutilized Features of .NET
15. Top 15 Underutilized Features of .NET Part 2
16. Neat Tricks for Effortlessly Format Currency in C#
17. Assert DateTime the Right Way MSTest NUnit C# Code
18. Which Works Faster- Null Coalescing Operator or GetValueOrDefault or Conditional Operator
19. Specification-based Test Design Techniques for Enhancing Unit Tests
20. Get Property Names Using Lambda Expressions in C#
21. Top 9 Windows Event Log Tips Using C#
If you enjoy my publications, feel free to SUBSCRIBE
Also, hit these share buttons. Thank you!
Source Code
The post- Assert DateTime the Right Way MSTest NUnit C# VB.NET Code appeared first on Automate The Planet.
All images are purchased from DepositPhotos.com and cannot be downloaded and used for free. License Agreement