Mocking DateTime.Now

June 10, 2009 Waldemar Mękal

We often use DateTime.Now without thinking, because it is easy and natural. However, this approach has one drawback. It tightly couples the application with the system clock. When it comes to testing, especially unit testing, we are in trouble.

How to cope with this? Quite easily. Just enclose DateTime.Now in a separate class just the way you should do with all external dependencies. The simplest method was proposed by Ayende Rahien.

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

And in code you use SystemTime.Now instead of DateTime.Now. When you need to mock it, you just use:

SystemTime.Now = () => new DateTime(2009, 1, 1);

Have fun!

Latest posts