Finding my ConnectionString in .NET Core integration tests

穿精又带淫゛_ 提交于 2019-12-10 14:19:45

问题


I'm building automated integration tests for my .NET Core project. Somehow I need to get access to a connection string for my integration tests database. The new .net core no longer has the ConfigurationManager, instead configurations are injected, but there is no way (at least not that I know of) to inject the connection string to a test class.

Is there any way in .NET Core that I can get at the configuration file without injecting something into a test class? Or, alternatively, is there any way that a test class can have dependencies injected into them?


回答1:


.NET Core 2.0

Create a new configuration and specify the correct path for your appsettings.json.

This is a part of my TestBase.cs which I inherit in all my tests.

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


来源:https://stackoverflow.com/questions/37577095/finding-my-connectionstring-in-net-core-integration-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!