Set environment in integration tests

Viewed 5327

I want to set environment in my integration tests using WebApplicationFactory. by defualt, env is set to Development. Code of my web application factory looks like this:

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup>
    where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseSolutionRelativeContentRoot(AppContext.BaseDirectory);

        base.ConfigureWebHost(builder);
    }

    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder()
            .UseStartup<TStartup>()
            .UseEnvironment("test"); // i want to launch `test` environment while im
                                     // testing my app
    }
}

When i start to debug Startup class (while i run tests) i still getting Development environment:

public Startup(IHostEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", false, true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
        // env.EnvironmentName is set to 'Development' while i set it to 'test'
        // in my WebApplicationFactory
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

How to set environment in WebApplicationFactory properly? Or maybe how to change strategy for tests only when in startup i depends on appsettings files?

4 Answers

I had the same issue and following worked out for me:

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
     builder.UseEnvironment("Test");
}

In your CustomApplicationFactory you should override CreateWebHostBuilder method with following code:

protected override IWebHostBuilder CreateWebHostBuilder()
{
    return base.CreateWebHostBuilder().UseEnvironment("test");
}

As an alternative, if you aren't using a custom WebApplicationFactory, you can specify the environment using the WithWebHostBuilder extension method:

var application = new WebApplicationFactory<Startup>()
    .WithWebHostBuilder(builder =>
    {
        builder.UseEnvironment("Test");
    });

Tested in .Net 6.0

Related