Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding my ConnectionString in .NET Core integration tests

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?

like image 277
Jeff Hornby Avatar asked Jun 01 '16 19:06

Jeff Hornby


1 Answers

.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();
    }
}
like image 117
Reft Avatar answered Oct 05 '22 09:10

Reft