English
A database for the tests
Step 1. The life of a test run
Why. Good tests are independent: each one starts from a known state, so the order of the tests does not matter and a failing test does not break the next one. With a database that means: an empty schema before every test. Creating a new database for every test would take seconds per test; Chatex combines three tools to make it fast (Fig. 6.2):
- Testcontainers starts a PostgreSQL container from code — once per test project — on a free port, and removes it after the run. Nothing has to be installed or started by hand, and the development database is never touched.
- The real migrations create the schema in that container, so every run also tests the migrations.
- Respawn empties all tables before each test with a few fast
DELETEstatements, keeping the schema. That takes milliseconds.
Fig. 6.2. One container per run, a clean database per test
Step 2. The fixture
Why. In xUnit, a fixture is an object shared by many tests, created before the first and disposed after the last. xUnit v3 adds assembly fixtures: one instance for all tests of a test project. That is the right scope for an expensive container.
Do. Create the fixture in Chatex.Testing:
cs
using Chatex.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;
using Respawn;
using Testcontainers.PostgreSql;
using Xunit;
namespace Chatex.Testing;
/// <summary>
/// Starts one PostgreSQL container per test assembly and applies the real migrations to it.
/// Register it with <c>[assembly: AssemblyFixture(typeof(PostgresFixture))]</c>.
/// </summary>
public sealed class PostgresFixture : IAsyncLifetime
{
private readonly PostgreSqlContainer _container = new PostgreSqlBuilder("postgres:18-alpine").Build();
private Respawner _respawner = null!;
public string ConnectionString => _container.GetConnectionString();
public async ValueTask InitializeAsync()
{
await _container.StartAsync();
var services = new ServiceCollection();
services.AddLogging();
services.AddData(ConnectionString, o => o.RootPath = Path.GetTempPath());
await using (var provider = services.BuildServiceProvider())
await using (var scope = provider.CreateAsyncScope())
{
await scope.ServiceProvider.GetRequiredService<ChatexDbContext>().Database.MigrateAsync();
}
await using var connection = new NpgsqlConnection(ConnectionString);
await connection.OpenAsync();
_respawner = await Respawner.CreateAsync(connection, new RespawnerOptions
{
DbAdapter = DbAdapter.Postgres,
SchemasToInclude = ["public"],
TablesToIgnore = ["__EFMigrationsHistory"],
});
}
/// <summary>Deletes all rows, keeping the schema.</summary>
public async Task ResetAsync()
{
await using var connection = new NpgsqlConnection(ConnectionString);
await connection.OpenAsync();
await _respawner.ResetAsync(connection);
}
public async ValueTask DisposeAsync() => await _container.DisposeAsync();
}IAsyncLifetimeis xUnit's interface for asynchronous setup and teardown:InitializeAsyncruns before the first test,DisposeAsyncafter the last. Both returnValueTask.new PostgreSqlBuilder("postgres:18-alpine").Build()describes the container with the same image ascompose.yaml;StartAsyncstarts it and waits until PostgreSQL accepts connections.GetConnectionString()returns the connection string with the random port Testcontainers chose, so tests never clash with the development database on port 5432.- The migrations are applied through the real registration: a temporary service collection calls
AddData, resolves the context and callsDatabase.MigrateAsync(). Theawait using (...)blocks dispose the provider and the scope as soon as the migration is done. - The
Respawnerinspects the database once and remembers the tables and the foreign keys between them, so thatResetAsynccan delete in the right order. It skips__EFMigrationsHistory, which must survive.
Step 3. A base class for database tests
Why. Every database test needs the same preparation: wipe the data, build a fresh service provider (so a fake registered by one test never leaks into the next), give the test a way to create scopes and resolve services. A base class does it once.
Do.
cs
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Chatex.Testing;
/// <summary>
/// Base for tests against <see cref="PostgresFixture"/>: wipes the database and builds a fresh service provider
/// (so fakes such as a test clock never leak between tests) before each test.
/// </summary>
public abstract class DatabaseTest(PostgresFixture fixture) : IAsyncLifetime
{
private ServiceProvider _services = null!;
protected static CancellationToken Ct => TestContext.Current.CancellationToken;
/// <summary>A temporary directory for file storage, deleted after the test.</summary>
protected string StorageRoot { get; } = Path.Combine(Path.GetTempPath(), "chatex-tests", Guid.NewGuid().ToString("N"));
protected abstract void ConfigureServices(IServiceCollection services, string connectionString);
public async ValueTask InitializeAsync()
{
await fixture.ResetAsync();
var services = new ServiceCollection();
services.AddLogging();
ConfigureServices(services, fixture.ConnectionString);
_services = services.BuildServiceProvider(validateScopes: true);
}
public async ValueTask DisposeAsync()
{
await _services.DisposeAsync();
if (Directory.Exists(StorageRoot))
{
Directory.Delete(StorageRoot, recursive: true);
}
GC.SuppressFinalize(this);
}
/// <summary>A fresh scope, i.e. a fresh DbContext with nothing tracked.</summary>
protected AsyncServiceScope NewScope() => _services.CreateAsyncScope();
protected static T Get<T>(AsyncServiceScope scope) where T : notnull =>
scope.ServiceProvider.GetRequiredService<T>();
/// <summary>Resolves a singleton (e.g. a fake) from the root provider.</summary>
protected T GetSingleton<T>() where T : notnull => _services.GetRequiredService<T>();
}abstractwith the abstract methodConfigureServices: each test project decides what to register — the data layer here, the business layer in topic 7. This is the template method pattern: the base class fixes the order of the steps, subclasses fill in one of them.InitializeAsyncruns before each test (xUnit creates a new instance of the test class for every test): reset the database, then build the provider.validateScopes: truemakes the container throw if a scoped service, such as the context, is resolved from the root provider — the mistake that would share one context between unrelated operations.NewScope()gives a test a fresh scope, which means a freshChatexDbContextwith nothing tracked. Tests use one scope to arrange data and another to act and assert, so that a result really comes from the database and not from the change tracker of the context that just saved it.Ctis the cancellation token of the running test (TestContext.Current.CancellationToken); xUnit cancels it when the run is aborted or times out. The analyzers of xUnit v3 remind you to pass it on.StorageRootis a temporary folder for file storage, deleted after the test.
Check
powershell
dotnet buildThe build succeeds again with zero warnings: the namespace Chatex.Testing exists now. There are still no tests.