Skip to main content

Time system

ITimeSystem wraps everything in the BCL that depends on the wall clock or makes a thread wait. Replace it with a MockTimeSystem in tests and you can fast-forward time without sleeping.

What it covers​

Sub-propertyWraps
DateTimeDateTime.Now, DateTime.UtcNow, DateTime.Today (plus MinValue, MaxValue, UnixEpoch)
DateTimeOffsetDateTimeOffset.Now, DateTimeOffset.UtcNow (plus MinValue, MaxValue, UnixEpoch)
StopwatchSystem.Diagnostics.Stopwatch
TaskTask.Delay
ThreadThread.Sleep
PeriodicTimerSystem.Threading.PeriodicTimer (.NET 8 or later)
TimerSystem.Threading.Timer
TimeZoneInfoSystem.TimeZoneInfo (Local, Utc, FindSystemTimeZoneById, GetSystemTimeZones)

Implementations​

TypePackageUse it for
RealTimeSystemTestably.AbstractionsProduction
MockTimeSystemTestably.Abstractions.TestingUnit tests
ITimeSystem timeSystem = new MockTimeSystem();

// any Thread.Sleep / Task.Delay / Stopwatch / Timer call goes through this instance
timeSystem.Thread.Sleep(TimeSpan.FromMinutes(5));
DateTime now = timeSystem.DateTime.Now; // advanced by 5 minutes

In this section​