Course contentsShow
← C#
Lesson 1700 of 1,90815. Software Quality and TestingFree lesson

Testing .NET Generic Host Features

Verify the startup behavior and health check registration of generic hosts.

In this lesson, you will learn how to verify that your IHost initializes correctly and registers expected health checks without needing to spin up a full-blown integration environment.

Validating Host Configuration

When building microservices or background workers, the HostBuilder is the backbone of your application. Testing it ensures that your dependency injection container is configured correctly and that essential services—like health checks—are actually present in the IServiceCollection.

Rather than starting the host (which can be slow and brittle), you can inspect the IServiceCollection directly during the configuration phase.

Verifying Health Check Registration

A common requirement is ensuring that critical dependencies have associated health checks. You can write a unit test that builds the host configuration and inspects the HealthCheckService options to confirm the expected checks are registered.

[Fact]
public void Host_ShouldRegisterDatabaseHealthCheck()
{
    // Arrange
    var builder = Host.CreateDefaultBuilder();
    builder.ConfigureServices((context, services) => {
        // Assume this extension method exists in your assembly
        services.AddMyApplicationServices(); 
    });

    // Act
    using var host = builder.Build();
    var options = host.Services.GetRequiredService<IOptions<HealthCheckServiceOptions>>();

    // Assert
    var isRegistered = options.Value.Registrations.Any(r => r.Name == "sql-server");
    Assert.True(isRegistered, "The SQL Server health check was not registered.");
}

Why Test Startup Logic?

Testing startup logic prevents "configuration drift." It is easy to accidentally remove a line from Program.cs or an extension method that registers a required background service. By inspecting the IServiceCollection post-build, you gain confidence that the container is wired as expected before the application ever attempts to process a request.

This approach allows you to catch registration bugs—such as missing environmental variables or mismatched interfaces—at the "test" stage rather than the "runtime" stage, keeping your deployment pipeline safe and your feedback loop fast.

Key Takeaway: Test your host’s health check registration and startup services by inspecting the IServiceCollection within the IHost instance to catch configuration errors before deployment.