Skip to content

Instantly share code, notes, and snippets.

@rasmuskl
Created July 8, 2013 08:53
Show Gist options
  • Save rasmuskl/5947275 to your computer and use it in GitHub Desktop.
Save rasmuskl/5947275 to your computer and use it in GitHub Desktop.
Mockable DateTime.UtcNow
public static class SystemTime
{
private static ITimeProvider _timeProvider = new RealTimeProvider();
public static DateTime UtcNow
{
get { return _timeProvider.UtcNow; }
}
public static IDisposable MockTime(DateTime utcNow)
{
var mockedTimeProvider = new MockedTimeProvider(utcNow, RestoreTimeProvider);
_timeProvider = mockedTimeProvider;
return mockedTimeProvider;
}
private static void RestoreTimeProvider()
{
_timeProvider = new RealTimeProvider();
}
private interface ITimeProvider
{
DateTime UtcNow { get; }
}
private class RealTimeProvider : ITimeProvider
{
public DateTime UtcNow { get { return DateTime.UtcNow; } }
}
private class MockedTimeProvider : ITimeProvider, IDisposable
{
private readonly Action _onDispose;
public DateTime UtcNow { get; private set; }
public MockedTimeProvider(DateTime utcNow, Action onDispose)
{
_onDispose = onDispose;
UtcNow = utcNow;
}
public void Dispose()
{
if (_onDispose != null)
{
_onDispose();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment