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

Handling Environment Specifics

Manage environment-aware testing configurations via appsettings profiles.

In this lesson, you will learn how to orchestrate environment-aware testing configurations by leveraging hierarchical appsettings profiles to ensure your tests behave predictably across development, staging, and CI/CD pipelines.

The Problem of Environment Drift

When testing, you often encounter situations where a test passes on your local machine but fails in the build server. This happens because infrastructure settings—like database connection strings, API base URLs, or feature flags—are hardcoded or inconsistently defined. Instead of polluting your test logic with if-else blocks based on the current environment, you should use the .NET configuration system to inject the correct settings at runtime.

Leveraging appsettings.{Environment}.json

To manage these specifics, organize your configuration files into profiles: appsettings.json (base defaults), appsettings.Development.json, and appsettings.Testing.json.

In your test project, you can use the Microsoft.Extensions.Configuration package to load these profiles based on an environment variable, typically ASPNETCORE_ENVIRONMENT.

public static IConfiguration InitConfiguration()
{
    var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
    
    return new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false)
        .AddJsonFile($"appsettings.{env}.json", optional: true)
        .AddEnvironmentVariables() // Allows CI/CD overrides
        .Build();
}

Implementing Environment-Aware Tests

By using the IConfiguration object, your tests remain decoupled from the specific environment. When running locally, the Development profile provides your local database string. In your CI/CD pipeline, you set ASPNETCORE_ENVIRONMENT to Testing, and the configuration provider automatically merges the appsettings.Testing.json values, overriding the defaults without changing a single line of test code.

Crucially, always include AddEnvironmentVariables() last in your configuration builder. This allows your CI/CD platform (like GitHub Actions or Azure DevOps) to inject secrets or specific connection strings directly into the process, keeping sensitive data out of your source-controlled JSON files entirely.

Key Takeaway: Use hierarchical configuration profiles and environment variables to inject infrastructure details at runtime, ensuring your tests remain environment-agnostic while executing against environment-specific dependencies.