Lesson 36 of 93 · 5 min read · Updated

Deterministic Time in .NET Tests with TimeProvider and FakeTimeProvider

Code that depends on the current time is hard to test when it reads DateTime.UtcNow directly. .NET 8 added TimeProvider, an abstract class that represents a clock, and the Microsoft.Extensions.TimeProvider.Testing package ships FakeTimeProvider for tests. This lesson uses them to test a night tariff at its exact boundary hours and to move time forward without waiting.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2
  4. Microsoft.Extensions.TimeProvider.Testing 11.0.0

The Class Under Test

TestablePriceService applies a 20 percent discount between 22:00 (inclusive) and 06:00 (exclusive). It asks its injected TimeProvider for the current time.

M05.TestableDesign/TestablePriceService.cs

public sealed class TestablePriceService(TimeProvider timeProvider, Func<int> jitterFactory)
{
/// <summary>Convenience constructor for callers that do not want jitter.</summary>
public TestablePriceService(TimeProvider timeProvider) : this(timeProvider, () => 0) { }

/// <summary>Hour the night tariff starts (inclusive).</summary>
public const int NightStartHour = 22;

/// <summary>Hour the night tariff ends (exclusive).</summary>
public const int NightEndHour = 6;

public decimal CalculateNightDiscountPrice(decimal basePrice)
{
var hour = timeProvider.GetUtcNow().Hour;
var isNight = hour >= NightStartHour || hour < NightEndHour;

return isNight
? decimal.Round(basePrice * 0.8m - jitterFactory(), 2, MidpointRounding.AwayFromZero)
: basePrice;
}
}

In production the class receives TimeProvider.System, which returns the real clock. Register it once in the container, for example as a singleton TimeProvider, and every class that asks for one gets the system clock. In a test you pass a FakeTimeProvider instead. The class code does not change.

Testing Boundary Hours with a Theory

Time rules break at their edges. Is 22:00 night or day? Is 06:00? A data-driven test makes each boundary an explicit row.

M05.TestableDesign.Tests/TimeProviderTests.cs

/// <summary>
/// In production : TimeProvider.System
/// In tests : FakeTimeProvider
///
/// This lets us test midnight, coupon expiry and timer limits
/// INSTANTLY, WITHOUT Thread.Sleep.
/// </summary>
public class TimeProviderTests
{
[Theory]
[InlineData(21, false)] // night tariff has not started yet
[InlineData(22, true)] // boundary: 22:00 is INCLUDED
[InlineData(3, true)] // night
[InlineData(5, true)] // boundary: before 06:00
[InlineData(6, false)] // boundary: 06:00 is EXCLUDED
[InlineData(14, false)] // daytime
public void CalculateNightDiscountPrice_DependsOnInjectedClock(int hour, bool expectDiscount)
{
// Arrange - we decide what time it is.
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 3, 14, hour, 0, 0, TimeSpan.Zero));
var sut = new TestablePriceService(clock);

// Act
var price = sut.CalculateNightDiscountPrice(100m);

// Assert
price.Should().Be(expectDiscount ? 80m : 100m);
}

new FakeTimeProvider(DateTimeOffset) creates a clock frozen at that instant. GetUtcNow() keeps returning the same value until the test moves it. The six rows cover the hour just before the window, both edges, and one value inside each region. If someone changes >= to > or < to <=, one of the boundary rows fails and names the hour in the test output.

Use TimeSpan.Zero as the offset. The service reads GetUtcNow(), so a UTC start instant keeps the hour in the test equal to the hour the service sees.

Moving Time Forward Without Waiting

Some behavior depends on time passing: a coupon expires, a cache entry ages out, a timer fires. With the real clock you would need Thread.Sleep or Task.Delay, which slows the suite and still does not give exact control. FakeTimeProvider.Advance moves the clock instantly.

M05.TestableDesign.Tests/TimeProviderTests.cs

[Fact]
public void Advance_MovesTimeForwardInstantly()
{
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 3, 14, 21, 59, 0, TimeSpan.Zero));
var sut = new TestablePriceService(clock);

sut.CalculateNightDiscountPrice(100m).Should().Be(100m);

// Move time forward by 1 minute - WITHOUT actually waiting.
clock.Advance(TimeSpan.FromMinutes(1));

sut.CalculateNightDiscountPrice(100m).Should().Be(80m);
}

The clock starts at 21:59, one minute before the tariff starts. The first call returns the full price. After Advance(TimeSpan.FromMinutes(1)) the clock reads 22:00 and the same instance returns the discounted price. The test runs in microseconds.

FakeTimeProvider also has SetUtcNow to jump to an absolute instant. When your code uses timeProvider.CreateTimer(...) or Task.Delay(delay, timeProvider), calling Advance fires those timers too, so timeout logic can be tested without real delays.

Controlling Randomness the Same Way

Time is not the only non-deterministic input. The same service takes a Func<int> for its random jitter. A test passes a constant, and the result becomes exact.

M05.TestableDesign.Tests/TimeProviderTests.cs

[Fact]
public void InjectedJitter_MakesEvenRandomnessDeterministic()
{
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 3, 14, 23, 0, 0, TimeSpan.Zero));

// We supply the randomness from outside as well -> full control.
var sut = new TestablePriceService(clock, jitterFactory: () => 3);

sut.CalculateNightDiscountPrice(100m).Should().Be(77m); // 100 * 0.8 - 3
}

Compare this with the legacy version of the same class, which read DateTime.UtcNow and a static Random. Its only possible test was a range assertion that passed for every outcome. Here every test asserts one exact value, and every test gives the same answer on a laptop at noon and on a CI agent at midnight.

The principle is the same for both inputs: anything that changes between runs must come from outside the class, so the test can fix its value.

Common Mistakes

  1. Mixing clocks. If a class takes a TimeProvider but one method still calls DateTime.UtcNow, the fake controls only part of the logic. Search the class for DateTime.Now, DateTime.UtcNow and DateTimeOffset.UtcNow after you introduce TimeProvider.
  2. Writing a custom IClock interface. Many older codebases have one. On .NET 8 and later, TimeProvider is the standard abstraction, it already has a test double, and libraries in the ecosystem accept it.
  3. Using local time by accident. GetLocalNow() depends on LocalTimeZone. If the code needs local time, set the fake's time zone in the test so the result does not depend on the build machine.

Summary

  1. TimeProvider is the built-in clock abstraction; production code receives TimeProvider.System.
  2. FakeTimeProvider starts at a fixed instant you choose, so time-based tests are repeatable.
  3. Use a [Theory] with one row per boundary hour to pin down inclusive and exclusive edges.
  4. Advance and SetUtcNow move time instantly and also fire timers, so tests never need Thread.Sleep.
  5. Treat randomness the same way: inject it as a function and pass a constant in tests.