skip to content

In an ASP.NET Core 10 grocery app, how do you unit test that a coupon expires at midnight by using TimeProvider and FakeTimeProvider?

level: seniorimportance: should knowfreq 38%

answer

  1. inject the clock, never DateTime.UtcNow
  2. Microsoft.Extensions.TimeProvider.Testing package
  3. starts at 2000-01-01 UTC, never moves alone
  4. Advance fires due timers; AdjustTime does not
  5. SetLocalTimeZone for the store's midnight

basics

~20 s

Make the coupon service read time from an injected TimeProvider, register TimeProvider.System in the app, and in tests pass a FakeTimeProvider set just before midnight; assert the coupon works, Advance past midnight, and assert it is rejected.

solid answer

~40 s

`System.TimeProvider` (since .NET 8) abstracts `GetUtcNow()`, `GetLocalNow()`, timestamps and timers. The app registers `TimeProvider.System` as a singleton and the coupon service takes `TimeProvider` in its constructor instead of reading `DateTime.UtcNow`. Tests use `FakeTimeProvider` from `Microsoft.Extensions.TimeProvider.Testing`: `new FakeTimeProvider(new DateTimeOffset(2026, 3, 31, 23, 59, 0, TimeSpan.Zero))` fixes the clock, and nothing moves until the test calls `Advance(TimeSpan.FromMinutes(2))` or `SetUtcNow(...)`. The parameterless constructor starts at midnight UTC on 1 January 2000, `AutoAdvanceAmount` defaults to zero, and `SetUtcNow` with an earlier time throws `ArgumentOutOfRangeException`. Its local time zone is UTC until `SetLocalTimeZone(...)`, which matters for a store's local midnight. Because `Task.Delay(TimeSpan, TimeProvider)`, `PeriodicTimer(TimeSpan, TimeProvider)` and `CancellationTokenSource(TimeSpan, TimeProvider)` create timers through the provider, `Advance` fires them deterministically; `AdjustTime` moves the clock without firing them.

code

csharp · 16 lines
csharp
using Microsoft.Extensions.Time.Testing;
using Xunit;

[Fact]
public async Task Coupon_is_rejected_after_midnight()
{
    var time = new FakeTimeProvider(new DateTimeOffset(2026, 3, 31, 23, 59, 0, TimeSpan.Zero));
    var service = new CouponService(new InMemoryCoupons(
        new Coupon("SPRING10", Percent: 10, ValidUntil: new DateOnly(2026, 3, 31))), time);

    Assert.True(await service.TryRedeemAsync("SPRING10", CancellationToken.None));

    time.Advance(TimeSpan.FromMinutes(2)); // 1 April, 00:01 UTC

    Assert.False(await service.TryRedeemAsync("SPRING10", CancellationToken.None));
}

go deeper

for a junior

Remember to inject TimeProvider instead of reading DateTime.UtcNow, and that tests pass a FakeTimeProvider whose clock they move.

for a middle

Explain FakeTimeProvider's start time, Advance versus SetUtcNow versus AdjustTime, and how the local time zone affects a midnight rule.

for a senior

Make timers, delays and cancellation timeouts provider-aware so background work is testable, and hunt down hidden real-clock calls.

for a principal

Adopt TimeProvider as the only time source across services so every date rule and schedule can be tested deterministically.

## The problem with DateTime.UtcNow A rule like "coupon `SPRING10` is valid until the end of 31 March" is easy to code with `DateTime.UtcNow` and impossible to test reliably that way: the result depends on when the test runs. Since .NET 8 the BCL offers an abstraction for exactly this, **`System.TimeProvider`**, an abstract class with `GetUtcNow()`, `GetLocalNow()`, `LocalTimeZone`, `GetTimestamp()`, `GetElapsedTime(...)` and `CreateTimer(...)`. `TimeProvider.System` is the real clock. ## Wiring it in the app 1. The coupon service takes `TimeProvider` in its constructor and calls `_time.GetUtcNow()` or `_time.GetLocalNow()` wherever it used `DateTime.UtcNow` or `DateTime.Now`. 2. `Program.cs` registers the real clock: `builder.Services.TryAddSingleton(TimeProvider.System);`. `TryAdd` avoids a duplicate, since some framework features (authentication, HTTP logging, `HybridCache`) already try-add the same singleton. 3. Delays and periodic work also take the provider: `Task.Delay(delay, _time, ct)`, `new PeriodicTimer(period, _time)`, `new CancellationTokenSource(timeout, _time)`, `task.WaitAsync(timeout, _time)`. ## FakeTimeProvider in the test `FakeTimeProvider` lives in the **`Microsoft.Extensions.TimeProvider.Testing`** package from dotnet/extensions. Its behaviour, as the source defines it: | Member | Behaviour | |---|---| | `new FakeTimeProvider()` | starts at 2000-01-01 00:00:00 UTC | | `new FakeTimeProvider(start)` | starts at the given `DateTimeOffset`, exposed as `Start` | | `GetUtcNow()` | returns the fake time; advances by `AutoAdvanceAmount`, default zero | | `Advance(delta)` | moves forward and fires timers that are now due; negative deltas throw | | `SetUtcNow(value)` | jumps forward and fires due timers; an earlier value throws `ArgumentOutOfRangeException` | | `AdjustTime(value)` | changes the clock without firing timers, like a system clock change | | `SetLocalTimeZone(tz)` | sets `LocalTimeZone`, which is UTC by default | The clock **never moves by itself**. A test that does not call `Advance` sees the same instant no matter how long it runs. ## Testing the midnight rule - Create the fake at 23:59 on the last valid day, call `TryRedeemAsync`, assert success. - `Advance(TimeSpan.FromMinutes(2))`, call again, assert the coupon is rejected as expired. - If "midnight" means the **store's** midnight, call `SetLocalTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin"))` and make the service compare against `GetLocalNow()` or convert explicitly. Without that, the fake's local zone is UTC, and a test written on a Berlin laptop and run on a UTC build agent still agrees, which is the point. - Add one case exactly at the boundary to pin down whether the limit is inclusive. ## Timers and background work Timer-driven code becomes deterministic too. A cleanup job that waits with `Task.Delay(TimeSpan.FromHours(1), _time, ct)` completes when the test calls `Advance(TimeSpan.FromHours(1))`; with `TimeProvider.System` it would wait an hour, and with `AdjustTime` it would keep waiting because that method shifts pending wake times along with the clock. Code that calls plain `Task.Delay(TimeSpan)` or `Thread.Sleep` bypasses the provider and stays on the real clock, so convert every time source, not just the reads of the current time. ## Elapsed time and polling loops - **Timestamps.** The fake's `GetTimestamp()` follows its clock, with a `TimestampFrequency` of one tick per 100 nanoseconds (`TimeSpan.TicksPerSecond`). Code that measures durations with `_time.GetTimestamp()` and `_time.GetElapsedTime(start)` therefore reports exactly the time the test advanced, which makes slow-path branches testable. - **Auto-advance.** Setting `AutoAdvanceAmount` makes every `GetUtcNow()` read move the clock by that amount. That suits code that polls the clock in a loop until a deadline; with the default of zero such a loop would spin forever in a test. ## Common mistakes - Injecting `TimeProvider` but still calling `DateTime.UtcNow` in a helper, which leaves a hidden real clock. - Expecting the fake to start at today's date; it starts in 2000 unless told otherwise, which breaks rules that compare with hard-coded dates. - Trying to go back in time with `SetUtcNow`; use a fresh provider or `AdjustTime`. - Asserting on log timestamps without giving `FakeLogCollectorOptions.TimeProvider` the same fake.

  • A nightly cleanup BackgroundService waits with Task.Delay(TimeSpan.FromHours(24)). How do you test one cycle quickly?
    Change the wait to `Task.Delay(TimeSpan.FromHours(24), _time, stoppingToken)` with an injected `TimeProvider`. In the test, start the service with a `FakeTimeProvider` and call `Advance(TimeSpan.FromHours(24))`; the delay's timer fires and the cycle runs without real waiting.
  • Why does the fake's default start date of 1 January 2000 sometimes break tests?
    Rules that compare with real-world dates, such as a coupon valid in 2026, see a clock decades earlier and fail or pass for the wrong reason. Pass an explicit start `DateTimeOffset` that sits next to the boundary being tested.

FakeTimeProvider is the clock on a theatre stage: it shows whatever time the stage manager sets, and it moves only when the stage manager moves it, while the audience's watches keep their own time.

  • FakeTimeProvider starts at the machine's current time when it is created.
  • FakeTimeProvider's clock advances slowly on its own during a test.
  • SetUtcNow can move the fake clock backwards to re-run a scenario.
  • AdjustTime fires due timers just like Advance does.
  • Plain Task.Delay(TimeSpan) honours the injected FakeTimeProvider automatically.