When running integration tests, I would like to use a partially randomly generated connection string for the DbContext where the database part of the connection string has a format like AppName_{RandomGuid}
. This would allow multiple integration test instances to run at the same time against a real database without anyone stepping on anyone else, as the integration test databases would be created, and destroyed as needed on the central dev database server. The entire connection string would look like Server=tcp:0.0.0.0,49172;Database=AppName_{RandomGuid};User Id=;Password=;TrustServerCertificate=True
.
What I have tried is something like this with the WebApplicationFactory
:
private static readonly WebApplicationFactory<Program> WebApplication = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
var testConfigurationSettings = new Dictionary<string, string>
{
{ $"Database:ConnectionString", $"Server=tcp:0.0.0.0,49172;Database=AppName_{Guid.NewGuid()};User Id=;Password=;TrustServerCertificate=True" }
};
var testConfiguration = new ConfigurationBuilder()
.AddInMemoryCollection(testConfigurationSettings)
.Build();
builder.UseConfiguration(testConfiguration);
});
This would work expect that in my Program.cs I have this line:
var builder = WebApplication.CreateBuilder(args);
// THIS LINE
builder.Configuration.AddJsonFile(path: $"appsettings.Development.{Environment.MachineName}.json", optional: true);
builder.Services.AddApplicationServices(builder.Configuration);
var app = builder.Build();
await app.RunAsync();
This allows developers (based on their machine name) to override their own settings as they want when running the application locally; importantly, each dev will have their own specific config file that, at a minimum, has a connection string which points to their own dev specific database. My problem with this solution is the line which adds the developer specific config is overriding the config registered in the WithWebHostBuilder
for the integration test, because, the Program.cs executes after the WithWebHostBuilder
code.
The first part is my actual problem, and the second is my current attempted solution which is so close, and clean to doing exactly what I want.