What's a good way to overwrite DateTime.Now during testing?

C#Unit TestingDatetimeTesting

C# Problem Overview


I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value?

C# Solutions


Solution 1 - C#

My preference is to have classes that use time actually rely on an interface, such as

interface IClock
{
    DateTime Now { get; } 
}

With a concrete implementation

class SystemClock: IClock
{
     DateTime Now { get { return DateTime.Now; } }
}

Then if you want, you can provide any other kind of clock you want for testing, such as

class StaticClock: IClock
{
     DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } }
}

There may be some overhead in providing the clock to the class that relies on it, but that could be handled by any number of dependency injection solutions (using an Inversion of Control container, plain old constructor/setter injection, or even a Static Gateway Pattern).

Other mechanisms of delivering an object or method that provides desired times also work, but I think the key thing is to avoid resetting the system clock, as that's just going to introduce pain on other levels.

Also, using DateTime.Now and including it in your calculations doesn't just not feel right - it robs you of the ability to test particular times, for example if you discover a bug that only happens near a midnight boundary, or on Tuesdays. Using the current time won't allow you to test those scenarios. Or at least not whenever you want.

Solution 2 - C#

Ayende Rahien uses a static method that is rather simple...

public static class SystemTime
{
    public static Func<DateTime> Now = () => DateTime.Now;
}

Solution 3 - C#

Using Microsoft Fakes to create a shim is a really easy way to do this. Suppose I had the following class:

public class MyClass
{
    public string WhatsTheTime()
    {
        return DateTime.Now.ToString();
    }

}

In Visual Studio 2012 you can add a Fakes assembly to your test project by right clicking on the assembly you want to create Fakes/Shims for and selecting "Add Fakes Assembly"

Adding Fakes Assembly

Finally, Here is what the test class would look like:

using System;
using ConsoleApplication11;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DateTimeTest
{
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestWhatsTheTime()
    {
        
        using(ShimsContext.Create()){

            //Arrange
            System.Fakes.ShimDateTime.NowGet =
            () =>
            { return new DateTime(2010, 1, 1); };

            var myClass = new MyClass();
            
            //Act
            var timeString = myClass.WhatsTheTime();

            //Assert
            Assert.AreEqual("1/1/2010 12:00:00 AM",timeString);
          
        }
    }
}
}

Solution 4 - C#

I think creating a separate clock class for something simple like getting the current date is a bit overkill.

You can pass today's date as a parameter so you can input a different date in the test. This has the added benefit of making your code more flexible.

Solution 5 - C#

The key to successful unit testing is decoupling. You have to separate your interesting code from its external dependencies, so it can be tested in isolation. (Luckily, Test-Driven Development produces decoupled code.)

In this case, your external is the current DateTime.

My advice here is to extract the logic that deals with the DateTime to a new method or class or whatever makes sense in your case, and pass the DateTime in. Now, your unit test can pass an arbitrary DateTime in, to produce predictable results.

Solution 6 - C#

Another one using Microsoft Moles (Isolation framework for .NET).

MDateTime.NowGet = () => new DateTime(2000, 1, 1);

> Moles allows to replace any .NET > method with a delegate. Moles supports > static or non-virtual methods. Moles > relies on the profiler from Pex.

Solution 7 - C#

I'd suggest using IDisposable pattern:

[Test] 
public void CreateName_AddsCurrentTimeAtEnd() 
{
    using (Clock.NowIs(new DateTime(2010, 12, 31, 23, 59, 00)))
    {
        string name = new ReportNameService().CreateName(...);
        Assert.AreEqual("name 2010-12-31 23:59:00", name);
    } 
}

In detail described here: http://www.lesnikowski.com/blog/index.php/testing-datetime-now/

Solution 8 - C#

Simple answer: ditch System.DateTime :) Instead, use NodaTime and it's testing library: NodaTime.Testing.

Further reading:

Solution 9 - C#

You could inject the class (better: method/delegate) you use for DateTime.Now in the class being tested. Have DateTime.Now be a default value and only set it in testing to a dummy method that returns a constant value.

EDIT: What Blair Conrad said (he has some code to look at). Except, I tend to prefer delegates for this, as they don't clutter up your class hierarchy with stuff like IClock...

Solution 10 - C#

I faced this situation so often, that I created simple nuget which exposes Now property through interface.

public interface IDateTimeTools
{
    DateTime Now { get; }
}

Implementation is of course very straightforward

public class DateTimeTools : IDateTimeTools
{
    public DateTime Now => DateTime.Now;
}

So after adding nuget to my project I can use it in the unit tests

enter image description here

You can install module right from the GUI Nuget Package Manager or by using the command:

Install-Package -Id DateTimePT -ProjectName Project

And the code for the Nuget is here.

The example of usage with the Autofac can be found here.

Solution 11 - C#

Have you considered using conditional compilation to control what happens during debug/deployment?

e.g.

DateTime date;
#if DEBUG
  date = new DateTime(2008, 09, 04);
#else
  date = DateTime.Now;
#endif

Failing that, you want to expose the property so you can manipulate it, this is all part of the challenge of writing testable code, which is something I am currently wrestling myself :D

Edit

A big part of me would preference Blair's approach. This allows you to "hot plug" parts of the code to aid in testing. It all follows the design principle encapsulate what varies test code is no different to production code, its just no one ever sees it externally.

Creating and interface may seem like a lot of work for this example though (which is why I opted for conditional compilation).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCraig.NicolView Question on Stackoverflow
Solution 1 - C#Blair ConradView Answer on Stackoverflow
Solution 2 - C#Anthony MastreanView Answer on Stackoverflow
Solution 3 - C#mmilleruvaView Answer on Stackoverflow
Solution 4 - C#MendeltView Answer on Stackoverflow
Solution 5 - C#Jay BazuziView Answer on Stackoverflow
Solution 6 - C#João AngeloView Answer on Stackoverflow
Solution 7 - C#Pawel LesnikowskiView Answer on Stackoverflow
Solution 8 - C#tugberkView Answer on Stackoverflow
Solution 9 - C#Daren ThomasView Answer on Stackoverflow
Solution 10 - C#Pawel WujczykView Answer on Stackoverflow
Solution 11 - C#Rob CooperView Answer on Stackoverflow