Files
work-club-manager/backend/WorkClub.Tests.Integration/Infrastructure/CustomWebApplicationFactory.cs

70 lines
2.5 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Testcontainers.PostgreSql;
using WorkClub.Infrastructure.Data;
namespace WorkClub.Tests.Integration.Infrastructure;
public class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class
{
private readonly PostgreSqlContainer _postgresContainer = new PostgreSqlBuilder()
.WithImage("postgres:16-alpine")
.WithDatabase("workclub_test")
.WithUsername("test")
.WithPassword("test")
.Build();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Start container (async wait)
_postgresContainer.StartAsync().GetAwaiter().GetResult();
builder.ConfigureAppConfiguration((context, config) =>
{
// Override connection string for tests
config.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:DefaultConnection"] = _postgresContainer.GetConnectionString()
});
});
builder.ConfigureServices(services =>
{
// Remove existing DbContext registration
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
// Add Testcontainers DbContext
services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(_postgresContainer.GetConnectionString()));
// Replace authentication with TestAuthHandler
services.RemoveAll<IAuthenticationSchemeProvider>();
services.AddAuthentication(defaultScheme: "Test")
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", options => { });
// Build service provider and ensure database created
var sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.EnsureCreated();
});
builder.UseEnvironment("Test");
}
public override async ValueTask DisposeAsync()
{
await _postgresContainer.DisposeAsync();
await base.DisposeAsync();
}
}