如何在.NET 6集成测试中使用AddInMemoryCollection?

Daa*_*aan 8 tdd integration-testing asp.net-core .net-6.0

关于如何开发 .NET 6 集成测试的文档。从逻辑上讲,我想通过更改配置参数来模拟外部依赖项(通常是引用某些外部系统而不是WireMock 服务器的url )。这可以通过名为AddInMemoryCollection的方法来完成。我在为 .NET 5 开发集成测试时一直在使用它。但是对于 .NET 6 应用程序(通常是没有 Startup 类的应用程序),我没有成功。

问题是我需要找到一种调用方法CreateClient,然后确保在调用代码AddInMemoryCollection之前调用Program.cs,以便在使用配置参数之前修改它们。我该怎么做呢?如何在.NET 6集成测试中正确使用AddInMemoryCollection?

这是一个不起作用的例子。AddInmemoryCollection不修改appsettings值。使用.NET 5这样的代码可以工作(但我只是参考启动)。

        [Fact]
        public void ActualTest()
        {
            TryAddInMemoryCollection("http://localhost:1234");
        }

        private void TryAddInMemoryCollection(string urlOnLocalhost)
        {
            var factory = new IntegrationWebApplicationFactory<Program>();
            factory.WithWebHostBuilder(whb =>
            {
                whb.ConfigureAppConfiguration((context, configbuilder) =>
                {
                    configbuilder.AddInMemoryCollection(new Dictionary<string, string>()
                     {
                         { "Google",urlOnLocalhost }
                     });
                });
            }).CreateClient();
        }
Run Code Online (Sandbox Code Playgroud)

在我的 Program.cs 中

    var googleLocation = builder.Configuration["Google"];
    Console.WriteLine($"GOOGLELOCATION!! {googleLocation}");
Run Code Online (Sandbox Code Playgroud)

小智 6

你可以这样做:

[Fact]
public void ActualTest()
{
    TryAddInMemoryCollection("http://localhost:1234");
}

private void TryAddInMemoryCollection(string urlOnLocalhost)
{
    var factory = new IntegrationWebApplicationFactory<Program>();
    factory.WithWebHostBuilder(whb =>
    {
       whb.UseSetting("Google",urlOnLocalhost);
    }).CreateClient();
}
Run Code Online (Sandbox Code Playgroud)

您还可以添加一个接受字典的扩展方法:

public static IWebHostBuilder UseSetting(this IWebHostBuilder builder, IDictionary<string, string> settings)
{
    foreach (var (key, value) in settings)
    {
        builder.UseSetting(key, value);
    }
    return builder;
}
Run Code Online (Sandbox Code Playgroud)