在集成测试中设置环境

时间:2020-07-15 09:53:53

标签: c# asp.net-core testing .net-core

我想使用WebApplicationFactory在集成测试中设置环境。通过defualt,env设置为Development。我的Web应用程序工厂的代码如下:

    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
        }
    }

当我开始调试Startup类时(运行测试时),我仍然得到Development环境:

        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();
        }

如何正确设置WebApplicationFactory中的环境?还是仅在启动时我才依靠appsettings文件来改变测试策略?

3 个答案:

答案 0 :(得分:0)

Host.CreateDefaultBuilder().ConfigureWebHost(e => e.UseEnvironment("Development"))

我从这些 URL 推断出解决方案:

https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1 https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-5.0

答案 1 :(得分:0)

在您的 CustomApplicationFactory 中,您应该使用以下代码覆盖 CreateWebHostBuilder 方法:

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

答案 2 :(得分:0)

我遇到了同样的问题,以下对我有用:

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