Add integration and unit tests for Notes API with PostgreSQL-based test hosting configuration

This commit is contained in:
Chuck Smith
2026-02-22 16:14:31 -05:00
parent 6a1aed8e13
commit 3d6df4f5df
11 changed files with 341 additions and 6 deletions

View File

@@ -0,0 +1,7 @@
namespace Freman.Sample.Web.IntegrationTests.TestHost;
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class IntegrationTestCollection : ICollectionFixture<IntegrationTestFixture>
{
public const string Name = "Integration tests";
}

View File

@@ -0,0 +1,43 @@
using Freman.Sample.Web.Data;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Testcontainers.PostgreSql;
namespace Freman.Sample.Web.IntegrationTests.TestHost;
public sealed class IntegrationTestFixture : WebApplicationFactory<Program>, IAsyncLifetime
{
private readonly PostgreSqlContainer _pg = new PostgreSqlBuilder("postgres:16")
.WithDatabase("testdb")
.WithUsername("appuser")
.WithPassword("testpassword")
.Build();
public SampleWebFactory Factory { get; private set; } = null!;
public async ValueTask InitializeAsync()
{
await _pg.StartAsync();
Factory = new SampleWebFactory(_pg.GetConnectionString());
// Apply migrations once
using var scope = Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
}
public new async ValueTask DisposeAsync()
{
await Factory.DisposeAsync();
await _pg.DisposeAsync();
}
public async Task ResetDatabaseAsync()
{
using var scope = Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.ExecuteSqlRawAsync(@"TRUNCATE TABLE notes RESTART IDENTITY;");
}
}

View File

@@ -0,0 +1,24 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
namespace Freman.Sample.Web.IntegrationTests.TestHost;
public sealed class SampleWebFactory(string connectionString) : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureAppConfiguration((_, config) =>
{
var overrides = new Dictionary<string, string?>
{
["ConnectionStrings:AppDb"] = connectionString,
["ApplyMigrationsOnStartup"] = "false"
};
config.AddInMemoryCollection(overrides);
});
}
}