Created
July 8, 2013 08:53
-
-
Save rasmuskl/5947275 to your computer and use it in GitHub Desktop.
Mockable DateTime.UtcNow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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