Testing time-dependent C# code with TimeProvider and FakeTimeProvider (.NET 8), Random and Guid

xUnit Testing & CI/CD in .NET November 13, 2026 csharp

Turn them into dependencies instead of static calls.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// ======================================================================
// Q: How do you test code that depends on time, random values or Guid?
//
// Turn them into dependencies instead of static calls. For time: TimeProvider
// (.NET 8+) and FakeTimeProvider in tests.
// Same idea for Random (a seed or an interface) and Guid (a generator interface,
// or only asserting that it is not Guid.Empty).
// ======================================================================

public class CreateOrderHandler(IOrderRepository orders, TimeProvider clock) { /* clock.GetUtcNow() */ }

[Fact]
public async Task Order_number_contains_creation_date()
{
    var clock = new FakeTimeProvider(new DateTimeOffset(2026, 11, 6, 10, 0, 0, TimeSpan.Zero));
    var handler = new CreateOrderHandler(orders, clock);

    var order = await handler.Handle(command, CancellationToken.None);

    Assert.StartsWith("ORD-20261106-", order.OrderNumber);
}

// Timeouts / retries without real waiting
clock.Advance(TimeSpan.FromMinutes(31));      // half an hour "passes" instantly