Testing time-dependent .NET code with the TimeProvider abstraction and FakeTimeProvider: injecting the clock, advancing virtual time, testing PeriodicTimer and Task.Delay, and avoiding races with asynchronous continuations.
I inject TimeProvider instead of reading DateTime.UtcNow. It is the built-in clock abstraction since .NET 8: GetUtcNow(), GetTimestamp(), CreateTimer() and LocalTimeZone. Production registers TimeProvider.System; tests use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing, where I call SetUtcNow or Advance(TimeSpan.FromDays(14)) to move virtual time instantly. Timers and delays also take the provider (Task.Delay(delay, time, ct), new PeriodicTimer(period, time)), so a one-hour schedule is tested in milliseconds.
Advance fires timers synchronously but continuations may run on another thread, so await a signal from a fake, not Thread.Sleep.The trade-off: one more constructor parameter, in exchange for tests that are fast, deterministic and independent of the day they run.
"Time is a hidden dependency. If a class calls
DateTime.UtcNowdirectly, I can't test a 14-day trial expiry without waiting 14 days or writing a test that passes today and fails on the 29th of February. Since .NET 8 the framework has a proper abstraction for it,TimeProvider. It gives meGetUtcNow(),GetTimestamp()for elapsed time,CreateTimer()and the local time zone. In production I registerTimeProvider.Systemas a singleton, and anything that cares about time takes aTimeProviderin its constructor. Timers and delays take it too:Task.Delay(delay, time, ct),new PeriodicTimer(period, time)andnew CancellationTokenSource(delay, time).In tests I use
FakeTimeProviderfromMicrosoft.Extensions.TimeProvider.Testing. I start it at a fixed instant, then callAdvanceorSetUtcNow. For a rule like trial expiry I test three points: one tick before, exactly at, and one tick after the boundary, because that is where off-by-one bugs between>and>=live. For a background job with aPeriodicTimer, I start the job, advance by one period, and assert that the work ran once; advance again and it ran twice. A test that covers an hour of schedule runs in a few milliseconds.The mistake I see is assuming
Advancemakes everything synchronous. It fires the timer callbacks on the calling thread, but the code awaitingWaitForNextTickAsyncusually resumes on the thread pool, so an assertion straight afterAdvancecan race. I have the fake dependency signal through a channel orTaskCompletionSourceand await that, with a real-time safety timeout so a bug fails the test instead of hanging CI. Virtual time for the logic, a real timeout only as a guard rail."
| Member / API | Replaces | Fake behaviour |
|---|---|---|
GetUtcNow() |
DateTimeOffset.UtcNow, DateTime.UtcNow |
Returns the fake's current instant |
GetLocalNow() / LocalTimeZone |
DateTime.Now, TimeZoneInfo.Local |
SetLocalTimeZone(...) |
GetTimestamp() / GetElapsedTime() |
Stopwatch |
Moves with Advance |
CreateTimer() |
System.Threading.Timer |
Fires when virtual time passes the due time |
Task.Delay(t, provider, ct) |
Task.Delay(t) |
Completes on Advance |
new PeriodicTimer(p, provider) |
PeriodicTimer(p) |
Ticks on Advance |
new CancellationTokenSource(t, provider) / CancelAfter |
real-time cancellation | Cancels on Advance |
| Method | Use it for |
|---|---|
new FakeTimeProvider(start) |
Fix the starting instant (default is 1 January 2000 UTC) |
SetUtcNow(instant) |
Jump to a specific date; cannot go backwards |
Advance(TimeSpan) |
Move forward and fire anything that became due |
AutoAdvanceAmount |
Every GetUtcNow() call moves time on, for code that loops until time changes |
SetLocalTimeZone(tz) |
Test AEST/AEDT daylight-saving transitions |
| Situation | Choice |
|---|---|
| Timestamp only written to a log | Leave it; not worth injecting |
Database-generated timestamps (SYSUTCDATETIME()) |
Test in an integration test, or move the rule into code |
| Business rule depends on "now" (expiry, cut-offs, schedules) | Always inject TimeProvider |
Legacy code with a custom IClock |
Fine to keep; adapt it to TimeProvider when touched |
A subscription service had a trial-expiry check written as DateTime.Now > start.AddDays(14) running on Azure App Service in Australia East. Because the host ran in UTC while the rule assumed local time, about [n] customers per day lost access up to 11 hours early. Switching to TimeProvider with UTC comparisons and three boundary tests (including an AEDT transition) fixed it, and the test class ran in under 50 ms instead of the previous suite's Thread.Sleep-based 4 seconds.
Checks whether the candidate can make time-dependent code deterministic with the modern .NET abstraction and understands the concurrency subtleties of testing timers.
Green flags
TimeProvider and FakeTimeProvider and the provider-aware Task.Delay / PeriodicTimer overloadsAdvance fires callbacks synchronously but continuations may be asynchronous, and synchronises on a signalConfigureTestServicesRed flags
Thread.Sleep in tests to wait for timersDateTime.Now and run the test at the right time"A test should give the same result every time it runs. Reading the wall clock breaks that in three ways:
The fix is the same as for any other dependency: make it explicit and replaceable.
System.TimeProvider is an abstract class (not an interface) shipped in .NET 8 and available to older targets through the Microsoft.Bcl.TimeProvider package. It was designed so the BCL itself could accept it:
+------------------------+
| TimeProvider | abstract
| GetUtcNow() |
| GetTimestamp() |
| TimestampFrequency |
| LocalTimeZone |
| CreateTimer(...) |
+-----------+------------+
|
+--------------+---------------+
| |
TimeProvider.System FakeTimeProvider
(wall clock, OS timers) (virtual clock, list of
scheduled timers)
Because it is a class with virtual members, TimeProvider.System is a ready singleton and you never write your own production implementation.
FakeTimeProvider keeps the current virtual instant and a list of waiters (timers created through CreateTimer). Advance(delta) does roughly this:
now = now + delta
while any waiter has dueTime <= now:
pick the earliest
invoke its callback (synchronously, on the calling thread)
if periodic: reschedule dueTime += period
Task.Delay(t, provider) and PeriodicTimer(p, provider) are built on provider.CreateTimer, so they complete when the callback runs. The subtle part is what happens after the callback:
Task.Delay completes a task; an await on it resumes either inline or on the thread pool depending on the awaiter.PeriodicTimer signals a value-task source configured to run continuations asynchronously, so the code after await timer.WaitForNextTickAsync() almost always runs on a thread-pool thread after Advance has returned.That is why an assertion directly after Advance can race. The robust pattern is to have the code under test call a fake that writes to a Channel or completes a TaskCompletionSource, and to await that in the test.
Use GetTimestamp() and GetElapsedTime(start) for durations (timeouts, latency), and GetUtcNow() for instants (expiry dates). The wall clock can jump (NTP correction, manual change); the timestamp is monotonic. The fake moves both together on Advance.
Store and compare instants in UTC. Convert to Australia/Sydney (or AUS Eastern Standard Time on Windows; .NET 6+ accepts IANA ids on both) only at the edge for display or for rules phrased in local time, such as "orders placed before 5 pm Sydney time ship today". Test those rules on the first Sunday of October and April, when AEST and AEDT switch, using SetLocalTimeZone or by passing the TimeZoneInfo explicitly. Note that Queensland and the Northern Territory have no daylight saving.
Program.cs: services.AddSingleton(TimeProvider.System);
Integration tests: factory.WithWebHostBuilder(b => b.ConfigureTestServices(
s => s.AddSingleton<TimeProvider>(fakeTime)));
Microsoft.Extensions.Resilience (Polly v8), Microsoft.Extensions.Caching.Hybrid, rate limiting and many ASP.NET Core components resolve TimeProvider from DI when present, so a single fake controls retries and cache expiry in integration tests too.
An extra virtual call per time read is a few nanoseconds; irrelevant outside very tight loops. The real cost is discipline: an analyser rule (for example BannedApiAnalyzers listing DateTime.Now, DateTime.UtcNow and DateTimeOffset.Now) keeps the wall clock from creeping back in.
TrialPolicy with DateTime.UtcNow, then refactor it to take TimeProvider; add before / at / after tests.PeriodicTimer loop and a test that asserts immediately after Advance. Run it 500 times (for i in {1..500}; do dotnet test; done or a [Theory] with 500 rows) and watch it fail occasionally; then fix it with a channel signal.AutoAdvanceAmount = TimeSpan.FromSeconds(1) and test a polling loop that waits until a deadline.Microsoft.CodeAnalysis.BannedApiAnalyzers with a BannedSymbols.txt that bans P:System.DateTime.Now and P:System.DateTime.UtcNow, and see the build fail.A trial-expiry rule and an hourly reminder job, both taking TimeProvider, with xUnit v3 tests that move virtual time.
// Billing/TrialPolicy.cs
namespace Billing;
public sealed record Trial(Guid UserId, DateTimeOffset StartedAt);
public sealed class TrialPolicy(TimeProvider time)
{
public static readonly TimeSpan Length = TimeSpan.FromDays(14);
// >= is deliberate: the trial ends exactly 14 days after it started.
public bool IsExpired(Trial trial) => time.GetUtcNow() >= trial.StartedAt + Length;
}
public interface IReminderSender
{
Task SendDueAsync(DateTimeOffset now, CancellationToken ct);
}
public sealed class ReminderJob(TimeProvider time, IReminderSender sender)
{
public async Task RunAsync(CancellationToken ct)
{
// The provider-aware constructor lets tests tick this timer with Advance.
using var timer = new PeriodicTimer(TimeSpan.FromHours(1), time);
while (await timer.WaitForNextTickAsync(ct))
{
await sender.SendDueAsync(time.GetUtcNow(), ct);
}
}
}
// Billing.Tests/TimeTests.cs
using System.Threading.Channels;
using Billing;
using Microsoft.Extensions.Time.Testing;
using Xunit;
namespace Billing.Tests;
public sealed class TrialPolicyTests
{
private static readonly DateTimeOffset Start = new(2026, 11, 1, 0, 0, 0, TimeSpan.Zero);
[Theory]
[InlineData(-1, false)] // one tick before the boundary
[InlineData(0, true)] // exactly at the boundary
[InlineData(1, true)] // one tick after
public void IsExpired_AtBoundary(long tickOffset, bool expected)
{
var time = new FakeTimeProvider(Start);
var policy = new TrialPolicy(time);
time.Advance(TrialPolicy.Length + TimeSpan.FromTicks(tickOffset));
Assert.Equal(expected, policy.IsExpired(new Trial(Guid.NewGuid(), Start)));
}
}
public sealed class ReminderJobTests
{
// A fake that signals each call, so the test awaits instead of sleeping.
private sealed class RecordingSender : IReminderSender
{
private readonly Channel<DateTimeOffset> _calls = Channel.CreateUnbounded<DateTimeOffset>();
public Task SendDueAsync(DateTimeOffset now, CancellationToken ct)
{
_calls.Writer.TryWrite(now);
return Task.CompletedTask;
}
public ValueTask<DateTimeOffset> NextCallAsync(CancellationToken ct) => _calls.Reader.ReadAsync(ct);
}
[Fact]
public async Task SendsOncePerHour()
{
var start = new DateTimeOffset(2026, 11, 1, 9, 0, 0, TimeSpan.Zero);
var time = new FakeTimeProvider(start);
var sender = new RecordingSender();
// Real-time guard rail: a bug fails in 5 s instead of hanging CI.
using var guard = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
guard.CancelAfter(TimeSpan.FromSeconds(5));
using var stop = new CancellationTokenSource();
var run = new ReminderJob(time, sender).RunAsync(stop.Token);
time.Advance(TimeSpan.FromHours(1));
Assert.Equal(start.AddHours(1), await sender.NextCallAsync(guard.Token));
time.Advance(TimeSpan.FromHours(1));
Assert.Equal(start.AddHours(2), await sender.NextCallAsync(guard.Token));
await stop.CancelAsync();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => run);
}
}
// Program.cs: one registration; everything else asks for TimeProvider.
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<TrialPolicy>();
DateTime.Now or DateTime.UtcNow inside business rules. Why it is wrong: the rule can't be tested at a chosen instant and depends on the host's time zone. Instead: inject TimeProvider and use GetUtcNow().IClock in a new .NET 10 codebase. Why it is wrong: the BCL timers, Task.Delay, Polly v8 and HybridCache understand TimeProvider, not your interface. Instead: use TimeProvider and FakeTimeProvider.FakeTimeProvider across tests (a static field or class fixture). Why it is wrong: virtual time only moves forward, so one test's Advance leaks into the next and results depend on order and parallelism. Instead: create a new fake, with an explicit start instant, in every test.Advance on code that awaits a PeriodicTimer. Why it is wrong: the continuation usually runs on the thread pool after Advance returns, so the test is flaky. Instead: await a signal from a fake (channel or TaskCompletionSource).CancellationToken, cancel it at the end, and await the loop task (assert it ends with OperationCanceledException); dispose the PeriodicTimer with using.Thread.Sleep or Task.Delay with real time to wait for a timer in a test. Why it is wrong: slow and still racy on a loaded CI agent. Instead: virtual time plus awaited signals; keep a real timeout only as a guard.> versus >= bug lives exactly at the boundary. Instead: test one tick before, at, and after.new Timer(...) or Task.Delay(delay) without the provider overload. Why it is wrong: the fake can't control it, so tests wait in real time. Instead: use provider.CreateTimer, Task.Delay(delay, provider, ct) or new PeriodicTimer(period, provider).DateTimeOffset in UTC and convert at the edge.TimeProvider in integration tests. Why it is wrong: the API under WebApplicationFactory still uses the real clock. Instead: ConfigureTestServices(s => s.AddSingleton<TimeProvider>(fake)).The senior move is to treat time like any other I/O dependency and make it a team rule, not a per-class decision: TimeProvider.System registered once, FakeTimeProvider in tests, and a banned-API analyser so DateTime.UtcNow fails the build in domain code. I write that down as a short ADR and a section in the testing guidelines (new fake per test, await signals not sleeps, always cancel and await background loops), and add it to the code-review checklist so it survives team changes. That gives one fake that controls business rules, resilience delays and cache expiry together in integration tests.
The second senior point is knowing the limits of virtual time. It makes time deterministic, not threads. Code with timers still has asynchronous continuations, so tests must synchronise on observable effects and clean up the loops they start. And rules that live in SQL (GETUTCDATE() defaults, temporal tables) are outside the fake's reach: either move the rule into code or cover it with an integration test.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
TimeProvider + FakeTimeProvider |
Any new .NET 8+ code with time rules or timers | One constructor parameter | Timestamps only used in logs |
Custom IClock |
Existing codebases that already use one | Doesn't control BCL timers | New code on .NET 8+ |
Pass now as a method parameter |
Pure functions (pricing, eligibility) | Caller must supply it | Code that owns timers or delays |
| Real time with short settings | Smoke tests of the real scheduler | Slow, flaky | Unit tests |
I measure success by suite duration and flake rate: a time-heavy test class should run in milliseconds and show zero retries over a few hundred CI runs.
Inject TimeProvider (registered as TimeProvider.System in DI) instead of calling DateTime.UtcNow or Task.Delay directly. In tests use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing: set a start time, call Advance to move time forward, and timers, delays and PeriodicTimer created from it fire deterministically with no real waiting. Test the boundaries (exactly at expiry, one tick either side), keep business time in UTC, and cover daylight-saving rules with a fake local time zone.
CancellationTokenSource.CreateLinkedTokenSource(a, b, ...) creates a new source that is cancelled when any of the given tokens is cancelled, and can also be cancelled itself (for example with CancelAfter). It is how you combine "the caller cancelled" with "my own timeout" or "the host is shutting down". You must dispose the linked source, because it registers callbacks on the parent tokens; forgetting to do that on long-lived tokens leaks memory. To report the right error, check which source fired: if the caller's token is cancelled, rethrow cancellation; if only your timeout fired, throw a TimeoutException.
Controlling time in an integration test makes results reproducible: a retry delay, a cache expiry and a business cut-off all move together, instead of depending on how fast the CI agent is. Register TimeProvider.System in Program.cs, then in the test call factory.WithWebHostBuilder(b => b.ConfigureTestServices(s => s.AddSingleton<TimeProvider>(fake))) with a FakeTimeProvider. Polly v8 pipelines from Microsoft.Extensions.Resilience, HybridCache and the ASP.NET Core rate limiters resolve TimeProvider from DI, so fake.Advance(...) fires retry delays, expires cache entries and moves your own rules at once. Without it, a retry test waits for real backoff delays (slow), and a cache test either sleeps or never sees an expiry. Code that uses new Timer or DateTime.UtcNow directly won't follow the fake, so ban those APIs with BannedApiAnalyzers: add the Microsoft.CodeAnalysis.BannedApiAnalyzers package and a BannedSymbols.txt (an AdditionalFiles item) listing P:System.DateTime.Now, P:System.DateTime.UtcNow and P:System.DateTimeOffset.UtcNow, which raises RS0030 at build time.
How to tell it (STAR)
**S:** At [company], our [notifications] service had a reminder-job test that failed about once in 40 CI runs, and the team had papered over it with automatic retries. **T:** I was asked to find out why, because the retries were also hiding other flaky tests. **A:** I ran the test 1,000 times on a throttled agent and reproduced it 23 times. The fake clock was fine: the test asserted straight after `Advance`, but `PeriodicTimer` resumes on the thread pool, so the assertion raced the job. I changed the fake to signal through a channel, awaited that with a real-time guard, and added a nightly repeat-run job for new tests. **R:** 2,000 runs passed with no failures, we removed the blanket retry, and the most-retried-test list dropped from [n] entries to [m] within a month.
Last updated 23 Nov 2026.