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

Environment Variable Injection

Configure integration test environments using strongly-typed configuration settings.

In this lesson, you will learn how to configure integration test environments dynamically using strongly-typed configuration settings injected via environment variables.

The Problem with Hard-Coded Configurations

When writing integration tests using WebApplicationFactory, relying on static appsettings.json files is brittle. If your tests require different database connection strings or API keys for different environments—or if you need to avoid committing secrets to source control—hard-coded values become a liability. We want our tests to behave like a production-ready application that consumes configuration from the hosting environment.

Leveraging Strongly-Typed Injection

Instead of manually manipulating configuration files, we can use the IConfigurationBuilder within our WebApplicationFactory to inject environment variables. By mapping these variables to a C# class (the Options Pattern), we ensure type safety throughout our test suite.

Consider a scenario where your service requires an ExternalServiceOptions class. You can inject these settings directly into the test server's host builder:

public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureAppConfiguration((context, config) =>
        {
            // Injecting environment variables directly into the test environment
            config.AddInMemoryCollection(new Dictionary<string, string> {
                {"ExternalService:ApiKey", "TEST_SECRET_KEY"},
                {"ExternalService:TimeoutSeconds", "30"}
            });
        });
    }
}

By adding these to the configuration builder, the .NET IOptions<ExternalServiceOptions> pattern will automatically bind these values. This allows your integration tests to swap out infrastructure dependencies (like shifting from a real API to a stubbed service) simply by changing the injected variables, rather than modifying the codebase.

Why This Matters

Using environment variables for integration tests mirrors the real-world deployment strategy of your application (e.g., using 12-factor app principles). It ensures that your test environment is truly isolated and that your code is strictly consuming configuration from the environment, making your integration tests more robust, portable, and secure.

Key Takeaway: Use environment variable injection during the ConfigureWebHost phase to decouple your integration tests from static configuration files, ensuring your settings remain flexible, secret-safe, and strongly-typed.