Blog Stats

Meta

Mocking DateTime.Now

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.