Skip to content

Instantly share code, notes, and snippets.

@danbarua
Created April 4, 2014 12:39
Show Gist options
  • Save danbarua/9973888 to your computer and use it in GitHub Desktop.
Save danbarua/9973888 to your computer and use it in GitHub Desktop.
SystemDateTime - a mockable implementation of System.DateTime.Now
/// <summary>
/// Provides a mockable implementation of System.DateTime.Now;
/// </summary>
public static class SystemDateTime
{
private static readonly Func<DateTime> DefaultProvider = () => DateTime.Now;
[ThreadStatic]
private static Func<DateTime> dateTimeProvider;
static SystemDateTime()
{
dateTimeProvider = DefaultProvider;
}
/// <summary>
/// Gets the current DateTime
/// </summary>
public static DateTime Now
{
get
{
return dateTimeProvider();
}
}
/// <summary>
/// Allows mocking of system date time in a using() block
/// </summary>
public static IDisposable MockDateTime(DateTime value)
{
dateTimeProvider = () => value;
return new ActionDisposable(() => dateTimeProvider = DefaultProvider);
}
/// <summary>
/// Creates an IDisposable that calls the given function when disposed.
/// Used to reset state to an initial value once a using() block completes.
/// </summary>
private class ActionDisposable : IDisposable
{
private readonly Action disposedCallback;
public ActionDisposable(Action disposedCallback)
{
this.disposedCallback = disposedCallback;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
disposedCallback();
}
}
}
[Fact]
public void can_mock_dateTime()
{
var mockDate = new DateTime(2014, 01, 14);
using (SystemDateTime.MockDateTime(mockDate))
{
Assert.Equal(mockDate, SystemDateTime.Now);
}
Assert.NotEqual(mockDate, SystemDateTime.Now);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment