Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can I mock DateTime now?

Use Typemock Isolator, it can fake DateTime. Now and won't require you to change the code under test.

How do you mock a DateTime now flutter?

You can just wrap DateTime. now() in a class with only a function that returns current. Then in the tests mock this class to return whatever you need to. @loshkin I agree.

Is DateTime now static?

DateTime. Today is static readonly . So supposedly it should never change once (statically) instantiated.


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.


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

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

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

        }
    }
}
}

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.


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.


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.