Lesson 4 of 8
TestContainers - Real Database in Tests
In-memory databases don't test real SQL: raw SQL queries, migrations, constraints, and stored procedures all fail silently. TestContainers spins up a real PostgreSQL/SQL Server container in Docker for tests, then tears it down automatically - real DB confidence with zero setup hassle.
TestContainers with PostgreSQL
// dotnet add package Testcontainers.PostgreSql
using Testcontainers.PostgreSql;
using Npgsql.EntityFrameworkCore.PostgreSQL;
// ━━ PostgreSQL test container - real database, real SQL ━━
public sealed class PostgresWebApplicationFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
.WithImage("postgres:16-alpine")
.WithDatabase("testdb")
.WithUsername("testuser")
.WithPassword("testpass")
.Build();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
// Remove existing DbContext
var descriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
if (descriptor is not null) services.Remove(descriptor);
// Use the real PostgreSQL container
services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(_postgres.GetConnectionString()));
});
}
public async Task InitializeAsync()
{
// Start container (pulled from Docker Hub if not cached)
await _postgres.StartAsync();
// Apply all migrations to the container DB
using var scope = Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync(); // real schema, real constraints
}
public new async Task DisposeAsync() => await _postgres.DisposeAsync();
}
// ━━ Tests against real PostgreSQL ━━
public class RealProductRepositoryTests(PostgresWebApplicationFactory factory)
: IClassFixture<PostgresWebApplicationFactory>
{
private readonly HttpClient _client = factory.CreateClient();
[Fact]
public async Task CreateProduct_UniqueSlugConstraint_Enforced()
{
// First create
var createReq = new { Name = "Unique Widget", Price = 9.99, CategoryId = Guid.NewGuid() };
var r1 = await _client.PostAsJsonAsync("/api/products", createReq);
r1.StatusCode.Should().Be(System.Net.HttpStatusCode.Created);
// Duplicate create - same name, same slug
var r2 = await _client.PostAsJsonAsync("/api/products", createReq);
r2.StatusCode.Should().Be(System.Net.HttpStatusCode.Conflict);
// This test ONLY works with a real DB (unique index constraint)
// In-memory DB would allow duplicates!
}
[Fact]
public async Task GetProducts_WithFullTextSearch_Works()
{
// Full-text search tests require real SQL Server/PostgreSQL
var r = await _client.GetAsync("/api/products?search=laptop");
r.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);
}
}
class AppDbContext2 { public Task MigrateAsync_Placeholder() => Task.CompletedTask; }Tip
Tip
Practice TestContainers Real Database in Tests in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of TestContainers Real Database in Tests from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with TestContainers Real Database in Tests is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?