I am creating some tests using TestServer which is bootstrap with a complex configuration as following:
var config = new ConfigurationBuilder()
.Build();
webHostBuilder = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.CaptureStartupErrors(true)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<MockLicenseStartup>()
.UseEnvironment("Development")
.UseUrls("http://locahost");
testServer = new TestServer(webHostBuilder);
Both in my "asp.net core" project and in my test project I have created multiple appsettings.json which is used to provide things like:
The issue I am facing is that my Configuration class, inside the MockLicenseStartup is not able to load any of the available appsettings.json.
The code used inside MockLicenseStartup.cs is this one:
public MockLicenseStartup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
When I call Configuration.GetConnectionString("") it throws an exception and if I inspect further I can see that no configuration has been loaded actually. Probably is a problem related to the relative/absolute path of .UseContentRoot(Directory.GetCurrentDirectory())
In Test Environment,
.SetBasePath(env.ContentRootPath)
env.ContentRootPath is different from production, it is set to the test project's bin directory if I remember correctly. So, it will not locate the appsettings.json file. unless you copy it there after build.
If you are projects folder structure does not change. you can just try to hard code the appsettings.json" path in these two lines to where these are located.
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true
if this works (it should), you can make it better by find the appsetting.json path in code.
Below is my own code which work in test environment.
var settingFilePath = getSettingFilePath(settingFileParentFolderName: "APIProject");
var builder = new ConfigurationBuilder()
.AddJsonFile(settingFilePath + _settingFileName, optional: true, reloadOnChange: true)
.AddJsonFile(settingFilePath + "appsettings.Development.json", optional: true);
var configuration = builder.Build();
getSettingFilePath() is just a function to locate the setting file path in the Startup Project folder.
Hope this help.
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