Click here to Skip to main content
11,703,438 members (73,871 online)
Click here to Skip to main content

Assert DateTime the Right Way MSTest NUnit C# VB.NET Code

, 18 Feb 2015 CPOL 4.1K 14
Rate this:
Please Sign up or sign in to vote.
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 kind of delta.

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 kind of 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 with 1 second difference. In most cases, 1 second is not a problem. So you need an assert method which 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 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.

C#

public enum DateTimeDeltaType
{
    Days,
    Minutes
}

VB.NET

Public Enum DateTimeDeltaType
	Days
	Minutes
End Enum

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

C#

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;
    }
}

VB.NET

Public NotInheritable Class DateTimeAssert
	Private Sub New()
	End Sub
	Public Shared Sub Validate(expectedDate As System.Nullable(Of DateTime), _
	actualDate As System.Nullable(Of DateTime), deltaType As DateTimeDeltaType, count As Integer)
		If expectedDate Is Nothing AndAlso actualDate Is Nothing Then
			Return
		ElseIf expectedDate Is Nothing Then
			Throw New NullReferenceException("The expected date was null")
		ElseIf actualDate Is Nothing Then
			Throw New NullReferenceException("The actual date was null")
		End If
		Dim expectedDelta As TimeSpan = GetTimeSpanDeltaByType(deltaType, count)
		Dim totalSecondsDifference As Double = Math.Abs((DirectCast(actualDate, _
		DateTime) - DirectCast(expectedDate, DateTime)).TotalSeconds)

		If totalSecondsDifference > expectedDelta.TotalSeconds Then
			Throw New Exception(String.Format("Expected Date: {0}, _
			Actual Date: {1} " & vbLf & "Expected Delta: {2}, _
			Actual Delta in seconds- {3} (Delta Type: {4})", expectedDate, _
			actualDate, expectedDelta, totalSecondsDifference, deltaType))
		End If
	End Sub

	Private Shared Function GetTimeSpanDeltaByType_
		(type As DateTimeDeltaType, count As Integer) As TimeSpan
		Dim result As TimeSpan = Nothing

		Select Case type
			Case DateTimeDeltaType.Days
				result = New TimeSpan(count, 0, 0, 0)
				Exit Select
			Case DateTimeDeltaType.Minutes
				result = New TimeSpan(0, count, 0)
				Exit Select
			Case Else
				Throw New NotImplementedException("The delta type is not implemented.")
		End Select

		Return result
	End Function
End Class

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:

C#

DateTimeAssert.Validate( 
    new DateTime(2014, 10, 10, 20, 22, 16),
    new DateTime(2014, 10, 11, 20, 22, 16),
    DateTimeDeltaType.Days,
    1);

VB.NET

DateTimeAssert.Validate( 
    new DateTime(2014, 10, 10, 20, 22, 16),
    new DateTime(2014, 10, 11, 20, 22, 16),
    DateTimeDeltaType.Days,
    1);

The post- Assert DateTime the Right Way MSTest NUnit C# VB.NET Code appeared first on Automate The Planet.

License

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

Share

About the Author

Anton Angelov
Tester / Quality Assurance Telerik - A Progress Company
Bulgaria Bulgaria
Anton Angelov is a Quality Assurance Architect at Telerik a Progress Company, a leading vendor of products that make the life of programmers easier. He is passionate about automation testing and designing test harness and tools, having the best industry development practices in mind. In addition, he is an active blogger and the founder of Automate The Planet. He strives to make the site one of the leading authorities in Automation Testing by presenting compelling articles, inspiring ardent discussions amongst the community. He is also one of the most-rated-answer authors of questions about Test Automation Frameworks (WebDriver) on Stack Overflow.

You may also be interested in...

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
professionalAnton 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
professionalAnton 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
professionalAnton 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
professionalAnton Angelov22-Feb-15 9:28 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 19 Feb 2015
Article Copyright 2015 by Anton Angelov
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid