using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Testcontainers.PostgreSql; public class StreetWebApplicationFactory : WebApplicationFactory, IAsyncLifetime where Program : class { private readonly PostgreSqlContainer dbTestContainer; public StreetWebApplicationFactory() { dbTestContainer = new PostgreSqlBuilder().WithImage("postgis/postgis:17-3.5").Build(); } protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { // Use the test database services.AddDbContext(options => options.UseNpgsql(dbTestContainer.GetConnectionString())); // Ensure the database is created before running the tests using var scope = services.BuildServiceProvider().CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.Database.EnsureCreated(); }); } public async Task InitializeAsync() { await dbTestContainer.StartAsync(); } async Task IAsyncLifetime.DisposeAsync() { await dbTestContainer.DisposeAsync(); } }