【问题标题】:Set environment in integration tests在集成测试中设置环境
【发布时间】:2020-07-15 09:53:53
【问题描述】:

我想使用WebApplicationFactory 在我的集成测试中设置环境。默认情况下,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 文件?

【问题讨论】:

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


【解决方案1】:

我遇到了同样的问题,以下为我解决了:

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

【讨论】:

    【解决方案2】:

    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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-09
        相关资源
        最近更新 更多