覆盖单个集成测试用例的模拟依赖关系

问题描述 投票:0回答:2

我一直在遵循 this 教程为我的项目编写集成测试。

执行以下操作,我可以使用依赖项的模拟版本覆盖应用程序的 DI 配置:

public class ApiWebApplicationFactory : WebApplicationFactory<Api.Startup>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        // Is be called after the `ConfigureServices` from the Startup
        // which allows you to overwrite the DI with mocked instances
        builder.ConfigureTestServices(services =>
        {
            services.AddTransient<IWeatherForecastConfigService, WeatherForecastConfigMock>();
        });
    }
}

有没有办法可以为单个测试用例覆盖这个模拟服务注册?

services.AddTransient<IWeatherForecastConfigService, WeatherForecastConfigMock>();

编辑:尝试1

我在测试用例中添加了以下内容,但它并没有覆盖默认的构建器设置。

new WebApplicationFactory<Startup>().WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(services =>
                {
                    var weatherForecast =
                        services.SingleOrDefault(s => s.ServiceType == typeof(IWeatherForecastConfigService));
                    services.Remove(weatherForecast);
                    services.AddScoped<IWeatherForecastConfigService, WeatherForecastConfigMockUnhappy>();
                });
            });
c# integration-testing xunit
2个回答
0
投票

通过在默认工厂上调用

WebApplicationFactory<TEntryPoint>.WithWebHostBuilder(Action<IWebHostBuilder>)
方法来获取新工厂。这将创建一个具有指定构建器操作的新工厂,并且不会影响原始工厂。


0
投票

每次测试能够拥有不同的 WebApplicationFactory 模拟依赖服务配置是我创建一个名为 DivertR 的测试框架的主要动机之一。 https://github.com/devodo/DivertR

也许这会帮助你实现你想做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.