Search code examples
.net-coreintegration-testingconnection-string

.env File With WebApplicationFactory


I am setting up integration tests for my company. Each developer is going to have their own "integration-test" db. My goal is to put a connection string into a .env file and throw that file into the .gitignore so these changes are kept out of source control. When I try to access the contents of the .env file from my WebApplicationFactory the variables are empty. Any ideas why this is? I'll paste the code, let me know if there is anything I can clarify

public class ApiWebApplicationFactory : WebApplicationFactory<Startup>
{
    public IConfiguration Configuration { get; private set; }

    protected override IHostBuilder CreateHostBuilder()
    {
        DotNetEnv.Env.Load();
        var builder = Host.CreateDefaultBuilder()
            .UseSerilog()
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureWebHostDefaults(x => { x.UseStartup<Startup>().UseTestServer(); });
        return builder;
    }
    
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        var devDb = Environment.GetEnvironmentVariable("DB_CONN");
        builder.UseEnvironment("IntegrationTest");
        Environment.SetEnvironmentVariable("DB_CONN",
            devDb);
        Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "IntegrationTest");
        // Is be called after the `ConfigureServices` from the Startup
        // which allows you to overwrite the DI with mocked instances
        builder.ConfigureTestServices(services =>
          {
              services.AddAuthentication("IntegrationTest")
                  .AddScheme<AuthenticationSchemeOptions, IntegrationTestAuthenticationHandler>("IntegrationTest",
                      options => { }
                  );
          });
    }
}

var devDb in ConfigureWebHost is null, why isn't it being populated?!


Solution

  • create custom appsettings file to use for your test environment appsettings.test.json and set the connection string.

    {
      "ConnectionStrings": {
        "DB_CONN": "Data Source...."
      }
    }
    
    

    Set IConfiguration to read the json file in WebApplicationFactory.CreateHostBuilder()

     Configuration = new ConfigurationBuilder()
                    .AddJsonFile("appsetting.test.json")
                    .Build();
    

    If your system is using appsettings then you can add it when creating the host.

    For setting environment variables based on the Configuration, you can manually set the variables in ConfigureWebHost(IWebHostBuilder builder)

     Environment.SetEnvironmentVariable("DB_CONN", Configuration.GetConnectionString("DB_CONN"));