Lesson 85 of 93 · 6 min read · Updated

Testcontainers in .NET: Testing Against a Real, Disposable PostgreSQL Database

Many integration tests run against SQLite or the EF Core InMemory provider because they are fast and need no setup. The price is fidelity: these providers do not behave like the database you run in production, so some tests pass for the wrong reason and some bugs never show up. Testcontainers solves this by starting a real PostgreSQL server in a Docker container for the test run and throwing it away afterwards. This lesson shows tests that only make sense against the real database engine.

Technical Requirements

  1. .NET 11 SDK
  2. Docker (Docker Desktop, Colima, or any engine the Docker CLI can reach)
  3. Testcontainers.PostgreSql 4.17.0
  4. Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3 (EF Core 10 runs on net11.0)
  5. xUnit 2.9.3 and FluentAssertions 7.2.2

The first run downloads the postgres:17-alpine image, which can take a minute. Later runs reuse the cached image and start in a few seconds.

Starting a Real PostgreSQL Server for the Tests

The test project declares the container in a fixture. The builder takes an explicit image tag, a database name and credentials. Build() only describes the container; nothing runs until StartAsync() is called.

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

// The image tag is passed to the constructor EXPLICITLY: "latest" is never used.
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder("postgres:17-alpine")
.WithDatabase("tickets")
.WithUsername("tester")
.WithPassword("tester-parolasi")
.WithCleanUp(true) // Remove the container when the tests finish.
.Build();

public string PostgresConnectionString => _postgres.GetConnectionString();

Two details matter here. First, Testcontainers maps the PostgreSQL port to a random free port on the host. You never hard-code localhost:5432; you read the connection string from the running container with GetConnectionString(). This is why the same test code works on your laptop and on a CI agent where port 5432 may already be taken. Second, WithCleanUp(true) makes sure the container is removed when the test run ends, so nothing leaks between runs.

The fixture builds an EF Core context from that connection string:

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

/// <summary>Connection details are read from the RUNNING container: the port is random.</summary>
public TicketDbContext CreateDbContext()
{
var options = new DbContextOptionsBuilder<TicketDbContext>()
.UseNpgsql(PostgresConnectionString)
.Options;

return new TicketDbContext(options);
}

How the fixture starts, shares and disposes the container is the subject of the next lessons. Here we focus on what a real database lets you test.

Verifying the Database's Own Error Codes

The tickets table has a unique index on Reference. With a real server you can check not only that saving a duplicate fails, but that it fails with the exact PostgreSQL error code your error handling depends on.

M10.ContainerApi.Tests/PostgresBehaviourTests.cs

[Fact]
public async Task UniqueIndex_IsEnforcedByPostgres_WithSpecificErrorCode()
{
await using var db = fixture.CreateDbContext();
db.Tickets.Add(NewTicket("DST-0001"));
await db.SaveChangesAsync();

db.ChangeTracker.Clear();
db.Tickets.Add(NewTicket("DST-0001"));

var act = async () => await db.SaveChangesAsync();

// REAL PostgreSQL error code: 23505 = unique_violation.
// This level of verification is only possible with the production provider.
var exception = (await act.Should().ThrowAsync<DbUpdateException>()).Which;
exception.InnerException.Should().BeOfType<PostgresException>()
.Which.SqlState.Should().Be("23505");
}

If your API translates 23505 into an HTTP 409 Conflict, this is the test that proves the translation sees the right code. The InMemory provider does not enforce unique indexes at all, and SQLite reports a different error type. Note the ChangeTracker.Clear() call: without it, EF Core would detect the duplicate key in memory and throw before the database is ever asked.

The Most Common Trap: LIKE Behaves Differently

This is the test that best explains why provider fidelity matters. In SQLite, LIKE is case-insensitive for ASCII text. In PostgreSQL, LIKE is case-sensitive, and you need ILIKE for a case-insensitive search. The application service uses EF.Functions.ILike for that reason:

M10.ContainerApi/Endpoints/TicketService.cs

public Task<List<Ticket>> SearchAsync(string term, CancellationToken cancellationToken = default) =>
db.Tickets
.AsNoTracking()
.Where(t => EF.Functions.ILike(t.Subject, $"%{term}%"))
.OrderBy(t => t.Reference)
.ToListAsync(cancellationToken);

The test checks both sides: the service finds a lower-case search term, and a plain LIKE query does not.

M10.ContainerApi.Tests/PostgresBehaviourTests.cs

[Fact]
public async Task Ilike_IsCaseInsensitive_WhileLikeIsCaseSensitive()
{
// CRITICAL PROVIDER DIFFERENCE:
// SQLite -> LIKE is case-INSENSITIVE for ASCII.
// Postgres-> LIKE is case-SENSITIVE; you need ILIKE for insensitivity.
// A test written against SQLite could NEVER catch this bug.
await using var db = fixture.CreateDbContext();
db.Tickets.AddRange(
NewTicket("DST-0001", "Kargo Gecikmesi"),
NewTicket("DST-0002", "Fatura Hatası"));
await db.SaveChangesAsync();

var service = new TicketService(db, fixture.CreateCache());

// ILIKE -> finds it even when we search in lower case.
(await service.SearchAsync("kargo")).Should().ContainSingle()
.Which.Reference.Should().Be("DST-0001");

// LIKE -> case-sensitive, so the lower-case term finds NOTHING.
var likeResults = await db.Tickets
.Where(t => EF.Functions.Like(t.Subject, "%kargo%"))
.ToListAsync();

likeResults.Should().BeEmpty("LIKE is case-sensitive in PostgreSQL");
}

Common mistake: a team writes the search with EF.Functions.Like, tests it against SQLite, and the test passes. In production on PostgreSQL, users who type in lower case get no results. The SQLite test did not just miss the bug, it confirmed the wrong behaviour. Running the same query against a real PostgreSQL container gives you the opposite and correct answer.

PostgreSQL Types: Arrays and timestamptz

The Ticket entity stores its tags in a PostgreSQL text[] column and its creation time as timestamp with time zone. Neither has a faithful equivalent in SQLite or InMemory.

M10.ContainerApi.Tests/PostgresBehaviourTests.cs

[Fact]
public async Task ArrayColumn_SupportsContainsQuery()
{
// PostgreSQL text[] column and an array query.
// Neither SQLite nor EF InMemory runs this the way production does.
await using var db = fixture.CreateDbContext();
db.Tickets.AddRange(
NewTicket("DST-0001", "Kargo", "lojistik", "acil"),
NewTicket("DST-0002", "Fatura", "muhasebe"));
await db.SaveChangesAsync();

var service = new TicketService(db, fixture.CreateCache());

var results = await service.ByTagAsync("acil");

results.Should().ContainSingle().Which.Reference.Should().Be("DST-0001");
}

[Fact]
public async Task TimestampWithTimeZone_RoundTripsAsUtc()
{
// timestamptz behaviour: Postgres stores the value as UTC.
await using var db = fixture.CreateDbContext();
db.Tickets.Add(NewTicket("DST-0001"));
await db.SaveChangesAsync();
db.ChangeTracker.Clear();

var reloaded = await db.Tickets.SingleAsync();

reloaded.CreatedAt.Should().Be(Now);
reloaded.CreatedAt.Offset.Should().Be(TimeSpan.Zero);
}

ByTagAsync uses t.Tags.Contains(tag), which Npgsql translates into a native array operator. The second test reloads the row after clearing the change tracker, so the value really comes from the database. It proves that a DateTimeOffset written as UTC comes back as UTC. Npgsql rejects a non-UTC offset for timestamptz, and you only learn that with the real driver.

Here is a short overview of what each test needs from the real engine:

TestWhy SQLite or InMemory cannot do it
UniqueIndex_IsEnforcedByPostgres_WithSpecificErrorCodeThere is no PostgreSQL error code 23505
Ilike_IsCaseInsensitive_WhileLikeIsCaseSensitiveSQLite LIKE is case-insensitive, so the result is reversed
ArrayColumn_SupportsContainsQueryNo text[] column and no array query
TimestampWithTimeZone_RoundTripsAsUtcNo timestamptz semantics

Summary

  1. Testcontainers starts a real, disposable database in Docker for your tests and removes it afterwards.
  2. Read the connection string from the running container; the host port is random, so the same code works locally and in CI.
  3. A real database lets you assert on behaviour the fakes cannot reproduce: error codes, array columns, timestamptz.
  4. SQLite LIKE is case-insensitive while PostgreSQL LIKE is case-sensitive; a test on the wrong provider can confirm a bug instead of catching it.
  5. Use Testcontainers where provider behaviour matters, and keep fast unit tests for logic that does not touch the database.