【问题标题】:How to update IOptions/configuration in AspNetCore integration tests?如何在 AspNetCore 集成测试中更新 IOptions/配置?
【发布时间】:2022-11-09 05:39:00
【问题描述】:

我有一个 AspNetCore Web 应用程序并编写集成测试以使用WebApplicationFactory(即https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests)在内存中运行服务器

像往常一样,应用程序服务是可配置的,换句话说,我们使用IOptions<> 注入到各种服务中。我想测试不同的配置场景,我会动态定义配置。例如:

public class EmailSenderOptions
{
    public string Sender { get; set; }
}

// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<EmailSenderOptions>(config.GetSection("EmailSender"));

// Test
[TestFixture]
public class EmailSenderTests
{
     WebApplicationFactory<MyStartup> SUT = //omitted...

     [TestCase("noreply@mycompany.com")]
     [TestCase("easy-hookup@hackersite.com")]
     public void TestSender(string sender)
     {
         var client = SUT.CreateClient();
         SUT.Configuration.Set("EmailSender:Sender", sender); // <-- how?
         
         await client.GetAsync("/email");
     }
}

我知道我可以为 IOptions 创建测试实现,但这会更加困难,尤其是在使用 IOptionsMonitor 的情况下。所以我正在寻找一种方法来覆盖配置价值观运行

【问题讨论】:

    标签: asp.net-core integration-testing asp.net-core-configuration


    【解决方案1】:

    我们可以从服务中获取IConfiguration,因为它在应用程序启动期间已经被主机构建器注册为单例。我们还可以使用索引器设置值。 “诀窍”是我们还需要调用 reload(它可以通过IConfigurationRoot 接口使用)来填充更改

    internal static void SetConfiguration(this WebApplicationFactory<TStartup> Sut, string key, string value)
    {
        var config = Sut.Services.GetRequiredService<IConfiguration>();
        if (config is IConfigurationRoot root)
        {
            root[key] = value;
            root.Reload();
        }
    }
    
    // Call like
    SUT.SetConfiguration("EmailSender:Sender", "sender@mail.com"); // <-- how?
    

    其他替代方法是创建自己的IConfigurationSource 并通过字典提供值。这也需要实现IConfigurationProvider,仍然需要调用reload。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 2014-01-04
      • 2019-12-06
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多