簡體   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