Koen about .Net

June 28, 2011

Thread safe DateTime for unit testing

Filed under: Development, dotnetmag, Testing — Tags: — koenwillemse @ 16:00

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.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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 )

Google+ photo

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

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: