Lesson 36 of 93 · 5 min read · Updated
Deterministic Time in .NET Tests with TimeProvider and FakeTimeProvider
On this page
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
- .NET 11 SDK
- xUnit 2.9.3
- FluentAssertions 7.2.2
- 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
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
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
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
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
- Mixing clocks. If a class takes a
TimeProviderbut one method still callsDateTime.UtcNow, the fake controls only part of the logic. Search the class forDateTime.Now,DateTime.UtcNowandDateTimeOffset.UtcNowafter you introduceTimeProvider. - Writing a custom
IClockinterface. Many older codebases have one. On .NET 8 and later,TimeProvideris the standard abstraction, it already has a test double, and libraries in the ecosystem accept it. - Using local time by accident.
GetLocalNow()depends onLocalTimeZone. 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
TimeProvideris the built-in clock abstraction; production code receivesTimeProvider.System.FakeTimeProviderstarts at a fixed instant you choose, so time-based tests are repeatable.- Use a
[Theory]with one row per boundary hour to pin down inclusive and exclusive edges. AdvanceandSetUtcNowmove time instantly and also fire timers, so tests never needThread.Sleep.- Treat randomness the same way: inject it as a function and pass a constant in tests.