在 .NET Core 集成测试中查找我的 ConnectionString
Finding my ConnectionString in .NET Core integration tests
我正在为我的 .NET Core 项目构建自动化集成测试。我需要以某种方式访问我的集成测试数据库的连接字符串。新的 .net 核心不再有 ConfigurationManager,取而代之的是注入配置,但是没有办法(至少我不知道)将连接字符串注入测试 class.
在 .NET Core 中有什么方法可以让我在不向测试中注入内容的情况下获取配置文件 class?或者,有没有什么方法可以让测试 class 注入依赖项?
.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();
}
}
我正在为我的 .NET Core 项目构建自动化集成测试。我需要以某种方式访问我的集成测试数据库的连接字符串。新的 .net 核心不再有 ConfigurationManager,取而代之的是注入配置,但是没有办法(至少我不知道)将连接字符串注入测试 class.
在 .NET Core 中有什么方法可以让我在不向测试中注入内容的情况下获取配置文件 class?或者,有没有什么方法可以让测试 class 注入依赖项?
.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();
}
}