I am currently writing an integration test to test my APIs using WebApplicationFactory.
I have created a CustomWebApplicationFactory. I want to read the default appsettings.json that is found in the main web project. I know this can be achieved as below:
private static readonly IConfigurationRoot _configuration; // Global
// Inside Constructor
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
_configuration = builder.Build();
// To get connectionstring
var connStr = _configuration.GetConnectionString("DefaultConnection");
In my case, I want to use appsettings.json by default. Is there a way I can retrieve the connectionstring by reading appsettings.json from main Web project without defining the AddJsonFile codes in the constructor?
Since I inject the WebApplicationFactory<Program> into my integration test classes, I use the following:
public class MyIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _app;
private readonly IConfiguration? _config;
public MyIntegrationTests(WebApplicationFactory<Program> app)
{
_app = app;
_config = app.Services.GetService<IConfiguration>();
}
}
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