Click here to Skip to main content
14,975,931 members
Articles / DevOps / Unit Testing
Technical Blog
Posted 18 Feb 2015

Tagged as


15 bookmarked

Assert DateTime the Right Way MSTest NUnit C# Code

Rate me:
Please Sign up or sign in to vote.
5.00/5 (11 votes)
15 Sep 2015CPOL2 min read
Code samples in C# how to assert DateTime with delta. Write your own Validator for MSTest or use built-in methods in NUnit.


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.

Image 1

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

public enum DateTimeDeltaType

Next, use the below class to assert DateTimes 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)
        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 - 

        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})",

    private static TimeSpan GetTimeSpanDeltaByType(DateTimeDeltaType type, int count)
        TimeSpan result = default(TimeSpan);

        switch (type)
            case DateTimeDeltaType.Days: 
                result = new TimeSpan(count, 0, 0, 0);
            case DateTimeDeltaType.Minutes: 
                result = new TimeSpan(0, count, 0);
            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 DateTimes subtraction.

The usage is pretty simple:

    new DateTime(2014, 10, 10, 20, 22, 16),
    new DateTime(2014, 10, 11, 20, 22, 16),

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 and cannot be downloaded and used for free. License Agreement


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Anton Angelov
CEO Automate The Planet
Bulgaria Bulgaria
CTO and Co-founder of Automate The Planet Ltd, inventor of BELLATRIX Test Automation Framework, author of "Design Patterns for High-Quality Automated Tests: High-Quality Test Attributes and Best Practices" in C# and Java. Nowadays, he leads a team of passionate engineers helping companies succeed with their test automation. Additionally, he consults companies and leads automated testing trainings, writes books, and gives conference talks. You can find him on LinkedIn every day.

Comments and Discussions

QuestionOr use a real assertion framework Pin
Dennis Doomen5-Mar-15 19:24
MemberDennis Doomen5-Mar-15 19:24 
AnswerRe: Or use a real assertion framework Pin
Anton Angelov6-Mar-15 8:06
MemberAnton Angelov6-Mar-15 8:06 
SuggestionSome alternative solution... Pin
Andreas Gieriet22-Feb-15 9:29
professionalAndreas Gieriet22-Feb-15 9:29 
AnswerRe: Some alternative solution... Pin
Anton Angelov22-Feb-15 9:36
MemberAnton Angelov22-Feb-15 9:36 
GeneralRe: Some alternative solution... Pin
Andreas Gieriet22-Feb-15 9:39
professionalAndreas Gieriet22-Feb-15 9:39 
SuggestionSuggestion Pin
sx200820-Feb-15 14:21
Membersx200820-Feb-15 14:21 
AnswerRe: Suggestion Pin
Anton Angelov20-Feb-15 21:55
MemberAnton Angelov20-Feb-15 21:55 
GeneralRe: Suggestion Pin
sx200822-Feb-15 9:07
Membersx200822-Feb-15 9:07 
AnswerRe: Suggestion Pin
Anton Angelov22-Feb-15 9:28
MemberAnton Angelov22-Feb-15 9:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.