Corey Coogan

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

  • Subscribe

  • Archives

  • Blog Stats

    • 71,118 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<DateTime> 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 [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: