我正在为我的 .NET Core 项目构建自动化集成测试。不知何故,我需要访问集成测试数据库的连接字符串。新的.net core不再有ConfigurationManager,而是注入配置,但是没有办法(至少我不知道)将连接字符串注入到测试类中。
.NET Core 中有没有什么方法可以让我在不向测试类注入某些内容的情况下获取配置文件?或者,有什么方法可以让测试类注入依赖项吗?
.NET核心2.0
创建新配置并指定 appsettings.json 的正确路径。
这是我在所有测试中继承的 TestBase.cs 的一部分。
public abstract class TestBase
{
protected readonly DateTime UtcNow;
protected readonly ObjectMother ObjectMother;
protected readonly HttpClient RestClient;
protected TestBase()
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
var connectionStringsAppSettings = new ConnectionStringsAppSettings();
configuration.GetSection("ConnectionStrings").Bind(connectionStringsAppSettings);
//You can now access your appsettings with connectionStringsAppSettings.MYKEY
UtcNow = DateTime.UtcNow;
ObjectMother = new ObjectMother(UtcNow, connectionStringsAppSettings);
WebHostBuilder webHostBuilder = new WebHostBuilder();
webHostBuilder.ConfigureServices(s => s.AddSingleton<IStartupConfigurationService, TestStartupConfigurationService>());
webHostBuilder.UseStartup<Startup>();
TestServer testServer = new TestServer(webHostBuilder);
RestClient = testServer.CreateClient();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)