首页 文章

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

提问于
浏览
6

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

在.NET Core中是否有任何方法可以在配置文件中获取而无需将某些内容注入测试类?或者,或者,测试类是否有任何方式可以将依赖项注入其中?

1 回答

  • 1

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

相关问题