Last active
June 16, 2023 02:50
-
-
Save CraftyFella/42f459f7687b0b8b268fc311e6b4af08 to your computer and use it in GitHub Desktop.
Static Clock.cs which allows overriding of time in tests (running in parallel) dotnet core friendly
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
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Example | |
{ | |
public static class Clock | |
{ | |
private static Func<DateTime> _utcNow = () => DateTime.UtcNow; | |
static AsyncLocal<Func<DateTime>> _override = new AsyncLocal<Func<DateTime>>(); | |
public static DateTime UtcNow => (_override.Value ?? _utcNow)(); | |
public static void Set(Func<DateTime> func) | |
{ | |
_override.Value = func; | |
} | |
public static void Reset() | |
{ | |
_override.Value = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tests written in xunit that proves the time's don't clash with each other:
output: