We’ve been using the construction of a wrapper class around the DateTime for unit testing which Ayende described here.
Today one of my colleagues discovered that there is a possibility to run multiple unittests in parallel. How to do that is described here. However, the approach we used with the SystemDateTime class no longer worked, since it uses a static field which caused problem with two tests running at the same time. I tweaked it a bit to fix this, so I wanted to share the code we use for it.
/// <summary>
/// Facade for the System.DateTime class that makes it possible to mock the current time.
/// </summary>
public static class SystemDateTime
{
[ThreadStatic]
private static Func<DateTime> now;
[ThreadStatic]
private static Func<DateTime> today;
/// <summary>
/// Returns the current time as a DateTime object.
/// </summary>
public static Func<DateTime> Now
{
get { return now ?? (now = () => DateTime.Now.Truncate()); }
set { now = value; }
}
/// <summary>
/// Gets the current date.
/// </summary>
public static Func<DateTime> Today
{
get { return today ?? (today = () => Now().Date); }
set { today = value; }
}
}
Hope it helps some of you.
Advertisement