Corey Coogan

Python, .Net, C#, ASP.NET MVC, Architecture and Design

  • Subscribe

  • Archives

  • Blog Stats

    • 112,312 hits
  • Meta

Archive for June 7th, 2009

Mocking DateTime.Now

Posted by coreycoogan on June 7, 2009


The problem is simple.  You have written some code that does some date calculation, comparison, etc. using DateTime.Now.   Now you want to write a unit test against some scenario to make sure the code acts as expected.  The question is how to do this in a repeatable, automated test environment?  For a single run or two, you may try to simply set your system date to the desired value and run your test, but that has some obvious limitations.

One idea that I really like comes from Ayende in a blog post that’s almost a year old.  His solution is so simple and elegant – create a static method that returns Func<DateTime>, which allows you to specify a default and easily override the value in a test with a new expression.

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

Now rather than use DateTime.Now, use SystemTime.Now. To override the value in a test it’s simple:

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

Posted in Architecture and Design, TDD | Tagged: , , | 1 Comment »