Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Configuration from WebApplicationFactory?

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?

like image 894
avi Avatar asked Feb 25 '26 03:02

avi


1 Answers

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>();
  }

}
like image 72
fix Avatar answered Feb 27 '26 03:02

fix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!