Finding my ConnectionString in .NET Core Integration Tests

I am creating automatic integration tests for my .NET Core project. Somehow I need to access the connection string for my integration test database. The new .net kernel no longer has a ConfigurationManager, configurations are inserted instead, but there is no way (at least not what I know) to inject a connection string into a test class.

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

+4
source share
1 answer

.NET Core 2.0

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

This is part of my TestBase.cs that I inherit from all of 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();
    }
}
+1
source

All Articles