Wednesday, August 5, 2009

Unit Tests That Involve Dates

How do you unit test some code that uses DateTime.Now? What if you want to move the day one week into the future and test that your logic works as expected.

There are a couple of options. Instead of using DateTime.Now straight in your code you can pass in a parameter to your method which is the date time that you want to use in your logic. This would mean when you call this method from a unit test you could pass in any date you want. The normal code will still just use DateTime.Now though. This is a bit messy but in some instances this is not too bad.

The other option is to create a static class like this,

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

This means you can replace the DateTime.Now calls in your code to SystemTime.Now(). This will default to being the equivalent of DateTime.Now,

SystemTime.Now()

In your unit test you can move the time on by five minutes like this,

SystemTime.Now = () => DateTime.Now.AddMinutes(5);

And then continue to unit test the code as though we are five minutes in the future.

No comments: