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?
.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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With