gpt4 book ai didi

c# - 在 .NET Core 集成测试中查找我的 ConnectionString

转载 作者:太空狗 更新时间:2023-10-29 21:56:49 25 4
gpt4 key购买 nike

我正在为我的 .NET Core 项目构建自动化集成测试。我需要以某种方式访问​​我的集成测试数据库的连接字符串。新的 .net 核心不再有 ConfigurationManager,取而代之的是注入(inject)配置,但没有办法(至少我不知道)将连接字符串注入(inject)测试类。

在 .NET Core 中,有没有什么方法可以在不向测试类中注入(inject)内容的情况下获取配置文件?或者,有没有什么方法可以让测试类注入(inject)依赖项?

最佳答案

.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();
}
}

关于c# - 在 .NET Core 集成测试中查找我的 ConnectionString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37577095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com