覆盖单个集成测试用例的模拟依赖关系
我一直在关注 此教程用于为我的项目编写集成测试。
执行以下操作,我可以使用依赖项的模拟版本覆盖我的应用程序的 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
编辑:尝试 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>();
});
});
I've been following this tutorial for writing integration tests for my project.
Doing the following I can override the DI configuration of my app using a mocked version of a dependency:
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>();
});
}
}
Is there a way I can override this mocked service registration for a single test case?services.AddTransient<IWeatherForecastConfigService, WeatherForecastConfigMock>();
edit: attempt 1
I've added the following in my test case but it isn't overriding the default builder setup.
new WebApplicationFactory<Startup>().WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
var weatherForecast =
services.SingleOrDefault(s => s.ServiceType == typeof(IWeatherForecastConfigService));
services.Remove(weatherForecast);
services.AddScoped<IWeatherForecastConfigService, WeatherForecastConfigMockUnhappy>();
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过调用
WebApplicationFactory.WithWebHostBuilder(Action)
默认工厂上的方法。这将使用指定的构建器操作创建一个新工厂,并且不会影响原始工厂。Get a new factory by calling
WebApplicationFactory<TEntryPoint>.WithWebHostBuilder(Action<IWebHostBuilder>)
method on your default factory. This creates a new factory with the specified builder action and does not affect the original factory.每个测试能够拥有不同的 WebApplicationFactory 模拟依赖服务配置是我创建一个名为 DivertR 的测试框架的主要动机之一。 https://github.com/devodo/DivertR
也许这会帮助你实现你想做的事情这里。
Being able to have different WebApplicationFactory mocked dependency service configurations per test is one of the main motivations for why I created a testing framework called DivertR. https://github.com/devodo/DivertR
Maybe this will help you achieve what you want to do here.