繁体   English   中英

将测试项目 appSettings 附加到 ASP.NET Core 集成测试

[英]Append test project appSettings to ASP.NET Core integration tests

我正在按照这些文档创建 ASP.NET Core 集成测试(基于 xUnit)。 我想用它自己的appsettings.json启动测试网络服务器。 我的缩写文件夹结构是:

\SampleAspNetWithEfCore
\SampleAspNetWithEfCore\SampleAspNetWithEfCore.csproj
\SampleAspNetWithEfCore\Startup.cs
\SampleAspNetWithEfCore\appsettings.json
\SampleAspNetWithEfCore\Controllers\*

\SampleAspNetWithEfCore.Tests\SampleAspNetWithEfCore.Tests.csproj
\SampleAspNetWithEfCore.Tests\IntegrationTests.cs
\SampleAspNetWithEfCore.Tests\appsettings.json

然后我有这些实用程序:

public static class ServicesExtensions
{
    public static T AddOptions<T>(this IServiceCollection services, IConfigurationSection section)
        where T : class, new()
    {
        services.Configure<T>(section);
        services.AddSingleton(provider => provider.GetRequiredService<IOptions<T>>().Value);

        return section.Get<T>();
    }
}

Startup.cs ConfigureServices(...)我这样做:

services.AddOptions<SystemOptions>(Configuration.GetSection("System"));

像这样引用appsettings.json部分:

"System": {
  "PingMessageSuffix": " suffix-from-actual-project"
}

到目前为止一切顺利:这是以强类型方式获取的。 我的控制器获得了一个反映 json 结构的SystemOptions实例,并且控制器正确使用了后缀。

问题在于构建集成测试 WebHost 我要运行的Startup从我的实际项目为是,拥有自己的appsettings.json设置,但由于设置的一个额外层我想appsettings.json添加从我测试的csproj,如果适用覆盖任何设置。 这是我在测试项目中的 appsettings:

"System": {
  "PingMessageSuffix": " suffix-from-test-appsettings"
}

这是我尝试过的:

public class CustomWebApplicationFactory : WebApplicationFactory<Startup>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder
            .UseStartup<Startup>()
            .ConfigureAppConfiguration(config => config
                .AddJsonFile("appsettings.json")
            );
    }
}

但是,这不起作用。 如果我在控制器中遇到断点,我只会看到基础项目中的设置。 控制器当前只回显配置值,逻辑上返回结果也不如预期。

该文档没有在页面上的任何地方提到“appsettings”。

底线:在运行 ASP.NET Core 集成测试时,如何从测试项目的 appsettings.json 文件中添加一层 appSettings?

是这样解决的:

  1. 对于测试项目中的appsettings.json设置属性:
    • Build ActionContent Build Action
    • Copy to Output DirectoryCopy if newer
  2. 像这样使用自定义的WebApplicationFactory

     public class CustomWebApplicationFactory : WebApplicationFactory<Startup> { protected override void ConfigureWebHost(IWebHostBuilder builder) { var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); // Note: ↓↓↓↓ builder.ConfigureTestServices(services => services.AddOptions<SystemOptions>(configuration.GetSection("System")) ); } }

瞧:它有效!

第一步是让ConfigurationBuilder轻松找到您的 json 文件。 第二步巧妙地使用...TestServices配置(如果您使用常规的ConfigureServices方法,它将在 Startup 的服务配置之前被调用并被覆盖)。

脚注:评论者(关于这个问题)提到在 SUT 项目中有一个appsettings.ci.json文件可能会更好,并通过环境控制事物(您可以通过启动设置或通过 WebHostBuilder 进行设置)。 文档链接到一些已关闭的 GitHub 问题,这些问题暗示了同样的事情: 871290607153 根据您的场景和品味,这可能是更好或更惯用的解决方案。

2020 年 2 月更新 - ASP.NET Core 3.0 及更高版本

您执行此操作的方式已更改,您需要使用 ConfigureAppConfiguration 委托。

public class HomeControllerTests : IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;

    public HomeControllerTests(WebApplicationFactory<Startup> factory)
    {
        var projectDir = Directory.GetCurrentDirectory();
        var configPath = Path.Combine(projectDir, "appsettings.json");

         //New              ↓↓↓              
        _factory = factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureAppConfiguration((context,conf) =>
            {
                conf.AddJsonFile(configPath);
            });

        });
     }
}

归功于: https : //gunnarpeipman.com/aspnet-core-integration-tests-appsettings/

单元测试项目和集成测试项目都需要自己的 appsettings。 我们称我们的 appsettings.Test.json

然后我们使用 Microsoft.Extensions.Configuration 来访问它们。 所以通常在测试中我会做类似的事情:

 private readonly IConfiguration _configuration;

    public HomeControllerTests()
    {
          _configuration = new ConfigurationBuilder()
           .AddJsonFile("appsettings.Test.json")
           .Build();
    }

然后通过以下方式引用此文件中的值:

_configuration["user:emailAddress"]

文件如下所示:

"user": { "emailAddress": "myemail.com", …...

对于您正在尝试执行的操作,您可能需要创建一个类似于我的 appsettings.test.json 文件,该文件位于您的主 apsettings 文件旁边。 然后,您需要测试环境,然后添加适当的 appsettings 文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM