代码之家  ›  专栏  ›  技术社区  ›  Jeff Hornby

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

  •  6
  • Jeff Hornby  · 技术社区  · 8 年前

    我正在为我的.NETCore项目构建自动化集成测试。不知何故,我需要访问集成测试数据库的连接字符串。新的.net核心不再具有ConfigurationManager,而是注入配置,但没有办法(至少我不知道)将连接字符串注入测试类。

    在.NETCore中,有没有什么方法可以在不向测试类注入内容的情况下获取配置文件?或者,是否有任何方法可以将依赖注入测试类中?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Reft    7 年前

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