Lesson 82 of 93 · 6 min read · Updated

Testing .NET Background Services at Two Levels with FakeTimeProvider

Background services are hard to test because they depend on time. A job that runs every minute seems to need a test that waits a minute, and a test that waits is slow and flaky. This lesson shows a design that avoids both: keep the loop thin, move the work into its own service, and let FakeTimeProvider drive the clock. You then test the work and the loop as units, and test the hosted service inside the real application, without a single fixed sleep.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Microsoft.Extensions.TimeProvider.Testing 11.0.0 (provides FakeTimeProvider)
  4. Microsoft.EntityFrameworkCore.Sqlite 11.0.0
  5. Microsoft.AspNetCore.Mvc.Testing 11.0.0
  6. FluentAssertions 7.2.2
  7. Docker is not required.

Thin Loop, Separate Work

The job deletes expired book reservations. It is split into two parts. IReservationCleaner does one iteration of work. ReservationCleanupService is the loop: it waits for the timer, opens a DI scope, calls the cleaner and records the result.

LevelWhat it provesHow
Unit: the workExpired reservations are deleted, active ones stay, the boundary (== now) counts as expiredExpiredReservationCleaner + SQLite + FakeTimeProvider
Unit: the loopIt does not run before the interval, and runs exactly once when the interval passesFake cleaner + FakeTimeProvider.Advance
HostThe service is registered in the real Program.cs and works with DI and EF CoreBooksApiFactory + factory.Clock.Advance + /health/reservation-cleanup
HostOn shutdown a long iteration is cancelled, so the app does not hangMinimal Host + StopAsync + a time budget

Here is the loop:

M09.IntegrationApi/Background/ReservationCleanup.cs

public sealed class ReservationCleanupService(
IServiceScopeFactory scopeFactory,
TimeProvider timeProvider,
ReservationCleanupStatus status,
ILogger<ReservationCleanupService> logger) : BackgroundService
{
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(1);

private PeriodicTimer? _timer;

public override Task StartAsync(CancellationToken cancellationToken)
{
_timer = new PeriodicTimer(Interval, timeProvider);
return base.StartAsync(cancellationToken);
}

public override void Dispose()
{
_timer?.Dispose();
base.Dispose();
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var timer = _timer ?? throw new InvalidOperationException("Servis StartAsync ile başlatılmalı.");

try
{
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await using var scope = scopeFactory.CreateAsyncScope();
var cleaner = scope.ServiceProvider.GetRequiredService<IReservationCleaner>();

var removed = await cleaner.CleanAsync(stoppingToken);
status.RecordRun(removed, timeProvider.GetUtcNow());
logger.LogInformation("Süresi dolan {Count} ayırma silindi.", removed);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
// The application is shutting down: cancellation is EXPECTED, not an error.
}
}
}

PeriodicTimer accepts a TimeProvider. With FakeTimeProvider, the timer only ticks when the test calls Advance. The cleaner is resolved from a new scope on every tick, because AppDbContext is scoped and a hosted service is a singleton.

Pitfall: Where You Create the Timer Decides Whether the Test Is Flaky

Notice that the timer is created in StartAsync, not in ExecuteAsync. That is deliberate. From .NET 10, BackgroundService starts ExecuteAsync on a background thread. If the timer were created inside ExecuteAsync, there would be a race between "the host has started" and "the timer exists". A test could call Advance before the timer was created, the tick would never arrive, and the test would fail now and then.

The first version of this service did exactly that. It failed in 4 of 12 runs. After moving the timer to StartAsync, it passed 25 of 25. Adding Thread.Sleep(100) before Advance would have hidden the race on a fast machine and kept it on a slow CI agent. The real fix is to make the order of events deterministic.

Unit Level: The Work and the Loop

The work test needs no host. It creates the cleaner with a SQLite context and a fake clock:

M09.IntegrationApi.Tests/BackgroundServiceUnitTests.cs

[Fact]
public async Task CleanAsync_RemovesExpiredReservations_AndKeepsActiveOnes()
{
// Arrange
await using var db = CreateDb();
db.Reservations.AddRange(
Reservation("gecmis@ornek.com", expiresAt: Start.AddMinutes(-5)),
Reservation("aktif@ornek.com", expiresAt: Start.AddMinutes(30)));
await db.SaveChangesAsync();

var cleaner = new ExpiredReservationCleaner(db, _clock);

// Act
var removed = await cleaner.CleanAsync(CancellationToken.None);

// Assert
removed.Should().Be(1);
(await db.Reservations.Select(r => r.CustomerEmail).ToListAsync())
.Should().Equal("aktif@ornek.com");
}

The loop test replaces the cleaner with a spy that counts calls and completes a task on the first one:

M09.IntegrationApi.Tests/BackgroundServiceUnitTests.cs

[Fact]
public async Task Service_RunsExactlyOnce_WhenOneIntervalElapses()
{
// Arrange
var cleaner = new SignallingCleaner();
using var service = CreateService(cleaner, out var status);
await service.StartAsync(CancellationToken.None);

// Act — before the interval: the timer does NOT fire (FakeTimeProvider is synchronous).
_clock.Advance(ReservationCleanupService.Interval - TimeSpan.FromSeconds(1));
cleaner.Calls.Should().Be(0);

// The remaining 1 second: the timer fires.
_clock.Advance(TimeSpan.FromSeconds(1));

// Assert — observable condition + BOUNDED wait (no Thread.Sleep).
await cleaner.FirstCall.WaitAsync(TimeSpan.FromSeconds(5));
cleaner.Calls.Should().Be(1);

await service.StopAsync(CancellationToken.None);
status.CompletedRuns.Should().Be(1);
status.LastRunAtUtc.Should().Be(Start + ReservationCleanupService.Interval);
}

The test moves time to one second before the interval and checks that nothing ran. Then it moves the last second. The work still runs on another thread, so the test waits for the spy's FirstCall task, with a five-second upper limit. On a normal machine that wait ends in milliseconds.

Host Level: Inside the Real Application

The integration test proves what the unit tests cannot: the service is registered in Program.cs, the DI scope works, and EF Core deletes real rows. The BooksApiFactory already replaces TimeProvider with its Clock, so the service never ticks unless a test asks it to. Other tests are not affected.

M09.IntegrationApi.Tests/BackgroundServiceIntegrationTests.cs

[Fact]
public async Task HostedService_RemovesExpiredReservations_WhenTheIntervalElapses()
{
// Arrange — the clock is read from the FakeTimeProvider the host uses.
var now = factory.Clock.GetUtcNow();
await using (var db = factory.CreateDbContext())
{
db.Reservations.AddRange(
new BookReservation { BookId = 1, CustomerEmail = "gecmis@ornek.com", ExpiresAtUtc = now.AddSeconds(30) },
new BookReservation { BookId = 1, CustomerEmail = "aktif@ornek.com", ExpiresAtUtc = now.AddHours(1) });
await db.SaveChangesAsync();
}

var runsBefore = (await GetStatusAsync()).CompletedRuns;

// Act — advance one interval: the timer fires inside the host.
factory.Clock.Advance(ReservationCleanupService.Interval);

// Assert — ask from outside until the service completes a run (at most 5 s).
var status = await EventuallyAsync(
GetStatusAsync, s => s.CompletedRuns > runsBefore, Timeout);

status.LastRemovedCount.Should().Be(1);
await using (var db = factory.CreateDbContext())
{
(await db.Reservations.Select(r => r.CustomerEmail).ToListAsync())
.Should().Equal("aktif@ornek.com");
}
}

The test reads progress through GET /health/reservation-cleanup, an endpoint that exposes ReservationCleanupStatus. It is useful for operations too. EventuallyAsync polls that endpoint every 25 ms until the condition holds or five seconds pass, then throws a TimeoutException with the last value. Compared to a fixed Task.Delay(2000), it finishes at once on a fast machine, does not give false alarms on a slow one, and never hangs.

A second host-level test starts a minimal Host with a cleaner that never finishes, calls StopAsync with a five-second budget, and asserts that the cleaner saw the cancellation and that shutdown finished well inside the budget. That proves the stoppingToken really reaches the work.

Summary

  1. Keep the hosted service loop thin and move each iteration into its own injectable service.
  2. Pass a TimeProvider to PeriodicTimer and drive it with FakeTimeProvider.Advance in tests.
  3. Create the timer in StartAsync; from .NET 10, creating it in ExecuteAsync introduces a race that makes tests flaky.
  4. Never use a fixed sleep. Wait for an observable condition with a bounded timeout.
  5. Test the work and the loop as units, and the registration, DI scope and shutdown behaviour at host level.