Corey Coogan

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

  • Subscribe

  • Archives

  • Blog Stats

    • 93,945 hits
  • Meta

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);
About these ads

One Response to “Mocking DateTime.Now”

  1. [...] Now how do you do things like mock out crazy dependencies, adjust the time in your favorite SystemTime implementation or just tweak the configuration on the [...]

Sorry, the comment form is closed at this time.

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: