📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you unit test code that depends on the current time in .NET 10? Explain TimeProvider and FakeTimeProvider, how you test expiry rules, timers and delays deterministically, and the gotchas when a timer continuation runs on another thread.

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.

Mid-Level Coding Intermediate background-services fake-time-provider testing time-dependent-code timeprovider xunit

🎯 Key points

  • DateTime.UtcNow / DateTimeOffset.Now are hidden static dependencies: tests become slow, flaky or date-dependent
  • TimeProvider (System, .NET 8+) abstracts GetUtcNow, GetTimestamp, CreateTimer and the local time zone; register TimeProvider.System as a singleton
  • FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) gives SetUtcNow, Advance and AutoAdvanceAmount; create a new instance per test so no virtual time carries over
  • Task.Delay(TimeSpan, TimeProvider, CancellationToken), PeriodicTimer(period, timeProvider) and CancellationTokenSource(delay, timeProvider) accept the provider
  • Advance fires due timers synchronously, but continuations (e.g. PeriodicTimer) may run asynchronously on the thread pool: await a signal, never Thread.Sleep
  • Test boundaries exactly: one tick before, at, and after expiry; test DST and time-zone rules with SetLocalTimeZone
  • Cancel and await long-running loops at the end of each test, with a real-time guard linked to TestContext.Current.CancellationToken
  • Team rule: TimeProvider everywhere, wall-clock APIs banned by analyser, checked in code review

⏱ 30-second answer

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.

  • Test the boundary: just before, exactly at, just after.
  • 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Time is a hidden dependency. If a class calls DateTime.UtcNow directly, 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 me GetUtcNow(), GetTimestamp() for elapsed time, CreateTimer() and the local time zone. In production I register TimeProvider.System as a singleton, and anything that cares about time takes a TimeProvider in its constructor. Timers and delays take it too: Task.Delay(delay, time, ct), new PeriodicTimer(period, time) and new CancellationTokenSource(delay, time).

In tests I use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing. I start it at a fixed instant, then call Advance or SetUtcNow. 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 a PeriodicTimer, 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 Advance makes everything synchronous. It fires the timer callbacks on the calling thread, but the code awaiting WaitForNextTickAsync usually resumes on the thread pool, so an assertion straight after Advance can race. I have the fake dependency signal through a channel or TaskCompletionSource and 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."


What TimeProvider covers

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

FakeTimeProvider controls

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

When not to bother

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

Production example

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.

🔍 What the interviewer is checking

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

  • Names TimeProvider and FakeTimeProvider and the provider-aware Task.Delay / PeriodicTimer overloads
  • Tests boundaries (before, at, after) and daylight-saving transitions
  • Knows Advance fires callbacks synchronously but continuations may be asynchronous, and synchronises on a signal
  • Registers the fake in integration tests through ConfigureTestServices

Red flags

  • Thread.Sleep in tests to wait for timers
  • Says "just use DateTime.Now and run the test at the right time"
  • Invents a custom clock interface without knowing the BCL one exists

📚 Learn in depth

1. Why time breaks tests

A test should give the same result every time it runs. Reading the wall clock breaks that in three ways:

  • Speed: testing a one-hour retry window means waiting an hour, or shortening it with a magic test-only setting.
  • Flakiness: a test that sleeps 100 ms and expects a 50 ms timer to have fired fails on a busy CI agent.
  • Date dependence: tests pass on most days and fail at month end, on 29 February, or during a daylight-saving change.

The fix is the same as for any other dependency: make it explicit and replaceable.

2. The TimeProvider abstraction

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.

3. How FakeTimeProvider fires timers

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.

4. Elapsed time versus wall-clock time

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.

5. Time zones and Australia

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.

6. Integrating with DI

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.

7. Costs

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.

Try it yourself

  1. Write a TrialPolicy with DateTime.UtcNow, then refactor it to take TimeProvider; add before / at / after tests.
  2. Write a 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.
  3. Set AutoAdvanceAmount = TimeSpan.FromSeconds(1) and test a polling loop that waits until a deadline.
  4. Test a "ships today if ordered before 5 pm Sydney" rule across the October daylight-saving change.
  5. Add Microsoft.CodeAnalysis.BannedApiAnalyzers with a BannedSymbols.txt that bans P:System.DateTime.Now and P:System.DateTime.UtcNow, and see the build fail.

💻 Code

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>();

⚠ Common mistakes

  • Mistake: Calling 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().
  • Mistake: Writing a custom 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.
  • Mistake: Sharing one 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.
  • Mistake: Asserting immediately after 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).
  • Mistake: Starting a timer loop in a test and never stopping it. Why it is wrong: the loop keeps running after the test ends, holds timers and fakes alive, and can fail a later test or hang the run. Instead: pass a CancellationToken, cancel it at the end, and await the loop task (assert it ends with OperationCanceledException); dispose the PeriodicTimer with using.
  • Mistake: 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.
  • Mistake: Testing only "well after expiry". Why it is wrong: the > versus >= bug lives exactly at the boundary. Instead: test one tick before, at, and after.
  • Mistake: Using 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).
  • Mistake: Comparing local times stored without an offset. Why it is wrong: daylight-saving changes make an hour disappear or repeat. Instead: store DateTimeOffset in UTC and convert at the edge.
  • Mistake: Forgetting to replace TimeProvider in integration tests. Why it is wrong: the API under WebApplicationFactory still uses the real clock. Instead: ConfigureTestServices(s => s.AddSingleton<TimeProvider>(fake)).

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions retries with backoff or token expiry Why: Checks they can apply virtual time to resilience and distributed-system timing, not just a single rule.
    How to answer

    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.

  2. When: Candidate mentions a real-time safety timeout linked to the test's token Why: Checks they know how to combine a caller's cancellation token with a timeout safely.
    How to answer

    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.

  3. When: Candidate mentions registering TimeProvider in DI Why: Checks they understand which framework components resolve TimeProvider from DI and how to override it in WebApplicationFactory.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Hourly reminder test fails one CI run in forty
Situation
A [notifications] service sends appointment reminders from a `BackgroundService` using `PeriodicTimer`. Its tests used `FakeTimeProvider`, but the team had added a retry-on-failure step to CI to keep the build green, hiding a flaky test that blocked [n] merges a week.
Signals
CI test reports showed `ReminderJobTests.SendsOncePerHour` failing with `Expected 1 call, received 0` roughly once in 40 runs; it always passed locally; the test-retry report listed it as the most-retried test in the repository.
Investigation
I ran the test 1,000 times in a loop on a constrained agent (`--blame` on, 2 CPUs) and reproduced 23 failures. Reading the test showed `time.Advance(TimeSpan.FromHours(1))` followed immediately by `Assert.Single(sender.Calls)`. Stepping through `PeriodicTimer` showed its continuation is scheduled on the thread pool, so on a busy agent the assertion ran before the loop body. The fake time was correct; the synchronisation was missing.
Resolution
Immediate: quarantined the test with a tracked issue so merges were unblocked. Fix: changed the fake sender to write each call to a `Channel` and the test to await `NextCallAsync` with a 5-second real-time guard linked to `TestContext.Current.CancellationToken`. 2,000 repeated runs then passed with zero failures.
Prevention
Added a short testing guideline: never assert straight after `Advance` on timer-driven code; await an observable effect. Added a nightly job that repeats new or changed tests 200 times to catch flakiness before merge, and removed the blanket CI retry so flaky tests surface instead of hiding.

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.

↩ Usually asked after

More in Senior Testing Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me