Lesson 85 of 93 · 6 min read · Updated
Testcontainers in .NET: Testing Against a Real, Disposable PostgreSQL Database
On this page
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
- .NET 11 SDK
- Docker (Docker Desktop, Colima, or any engine the Docker CLI can reach)
Testcontainers.PostgreSql4.17.0Npgsql.EntityFrameworkCore.PostgreSQL10.0.3 (EF Core 10 runs onnet11.0)- 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
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
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
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
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
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
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:
| Test | Why SQLite or InMemory cannot do it |
|---|---|
UniqueIndex_IsEnforcedByPostgres_WithSpecificErrorCode | There is no PostgreSQL error code 23505 |
Ilike_IsCaseInsensitive_WhileLikeIsCaseSensitive | SQLite LIKE is case-insensitive, so the result is reversed |
ArrayColumn_SupportsContainsQuery | No text[] column and no array query |
TimestampWithTimeZone_RoundTripsAsUtc | No timestamptz semantics |
Summary
- Testcontainers starts a real, disposable database in Docker for your tests and removes it afterwards.
- Read the connection string from the running container; the host port is random, so the same code works locally and in CI.
- A real database lets you assert on behaviour the fakes cannot reproduce: error codes, array columns,
timestamptz. - SQLite
LIKEis case-insensitive while PostgreSQLLIKEis case-sensitive; a test on the wrong provider can confirm a bug instead of catching it. - Use Testcontainers where provider behaviour matters, and keep fast unit tests for logic that does not touch the database.