ASP.NET Core XUnit用参数(DI)替换服务



我是XUnit的新手,我正在尝试用新的应用程序设置和服务配置我的测试项目。该服务接受构造函数中的appsettings类。

在我的api项目的启动文件中,我有以下内容:

services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
var appSettings = _configuration.GetSection(nameof(AppSettings)).Get<AppSettings>();
services.AddScoped<ILogging, MailLogging>(s => new MailLogging(appSettings));           

这适用于我的API,但现在我想在我的XUnit项目中使用它(但使用不同的appsettings文件(

var appsettings = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build()
.GetSection("AppSettings");
builder.ConfigureTestServices(services =>
services.Configure<AppSettings>(appsettings)
);

这是可行的,但当我尝试实现新的MailLogging时,在使用服务中的AppSettings中的数据时,我会得到NullExceptions。(评论中的两行都不起作用(

builder.ConfigureTestServices(services =>
//services.AddScoped<ILogging, MailLogging>(s => new MailLogging(appsettings as AppSettings))
//services.Replace(ServiceDescriptor.Scoped<ILogging, MailLogging>(s => new MailLogging(appsettings as AppSettings)))
);

有人能给我指正确的方向吗?

改为尝试绑定方法:

var appsettingsSection = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build()
.GetSection("AppSettings");
var appSettings = new AppSettings();
appsettingsSection.Bind(appSettings);
builder.ConfigureTestServices(services =>
services.AddSingleton(appSettings);
services.AddScoped<ILogging, MailLogging>(s => new MailLogging(appsettings)
);

最新更新