skip to content

With Testcontainers for .NET, what does new PostgreSqlBuilder("postgres:17").Build() give you, and how does a test connect to it?

level: juniorimportance: should knowfreq 42%

answer

  1. a container object, not yet running
  2. await StartAsync() to run it
  3. postgres / postgres / postgres
  4. random host port for 5432
  5. parameterless constructor is [Obsolete]

basics

~20 s

Build() returns a PostgreSqlContainer that is configured but not running. After await StartAsync(), GetConnectionString() returns a Host, Port, Database, Username and Password string pointing at the container's randomly mapped port, which the test passes to its DbContext or app.

solid answer

~40 s

`new PostgreSqlBuilder("postgres:17")` is the Testcontainers PostgreSQL module builder, and `Build()` returns a `PostgreSqlContainer` that has not started yet. `await container.StartAsync()` pulls the image, starts it and waits until `pg_isready` answers. The module has already chosen database `postgres`, user `postgres`, password `postgres`, and a **random host port** for 5432, so the test never hard-codes an address: it calls `GetConnectionString()` after start and hands the result to `UseNpgsql` or to the app's configuration. Calling it before start throws `InvalidOperationException`. The image goes in the constructor because in Testcontainers 4.15 the parameterless constructor is obsolete; the old default was `postgres:15.1`. `MsSqlBuilder` works the same way, with `sa`, the `master` database and `TrustServerCertificate=True` in its string. `DisposeAsync()` stops and removes the container.

code

csharp · 12 lines
csharp
await using var db = new PostgreSqlBuilder("postgres:17")
    .WithDatabase("orders")
    .Build();                      // described, not running

await db.StartAsync();             // pulls, starts, waits for pg_isready

var options = new DbContextOptionsBuilder<OrdersDbContext>()
    .UseNpgsql(db.GetConnectionString())   // Host=...;Port=<random>;Database=orders;...
    .Options;

await using var context = new OrdersDbContext(options);
await context.Database.MigrateAsync();

go deeper

for a junior

Recall the sequence: builder with an image, Build(), await StartAsync(), GetConnectionString(), and DisposeAsync() at the end. Never type the port yourself.

for a middle

Explain what the module configures that a plain container would not: the random port binding, the default credentials, the pg_isready wait and the durability settings.

for a senior

Pin the image to production's major version, treat the obsolete parameterless constructor as a defect, and make sure nothing in the suite assumes localhost or a fixed port.

for a principal

Decide how image versions are upgraded across many test projects, for example one shared constant reviewed alongside the production database upgrade.

## Builder, container, start Testcontainers for .NET separates **describing** a container from **running** it. - A **builder** is an immutable description. Every `With...` call returns a new builder. The PostgreSQL module ships `PostgreSqlBuilder` in the `Testcontainers.PostgreSql` package; SQL Server's is `MsSqlBuilder` in `Testcontainers.MsSql`. - `Build()` validates the description and returns a **container object**, here a `PostgreSqlContainer`. Nothing has happened in Docker yet. - `await StartAsync()` pulls the image if needed, creates and starts the container, and returns only when the module's **wait strategy** says the database accepts connections. - `await DisposeAsync()` stops and removes it. ## What the PostgreSQL module configures A generic container would need you to set the port, the environment variables and a readiness check yourself. The module does it in its `Init()`: 1. binds container port **5432 to a random free host port**, so parallel test runs never collide; 2. sets `POSTGRES_DB`, `POSTGRES_USER` and `POSTGRES_PASSWORD` to `postgres` (change them with `WithDatabase`, `WithUsername`, `WithPassword`); 3. starts the server with `fsync=off`, `full_page_writes=off` and `synchronous_commit=off`, trading crash safety the tests do not need for speed; 4. waits by running `pg_isready` inside the container until it succeeds. `ExecScriptAsync(sql)` copies a SQL script into the container and runs it with `psql`, which is handy for seeding reference data. ## Connecting a test `GetConnectionString()` assembles `Host=<docker host>;Port=<mapped port>;Database=postgres;Username=postgres;Password=postgres`. The port is only known after start, which is why: - the call must come **after** `StartAsync()`; before it, Testcontainers throws `InvalidOperationException` saying the resource does not exist yet; - a test must never assume port 5432 on localhost; the host may also not be localhost when Docker runs remotely. The string then goes wherever the code under test reads it: `new DbContextOptionsBuilder<OrdersDbContext>().UseNpgsql(cs)` for a DbContext-level test, or the `ConnectionStrings:Orders` setting of a `WebApplicationFactory<Program>` for an HTTP-level test. ## The explicit image In Testcontainers 4.15 the parameterless constructors of the module builders and their default-image constants, such as `PostgreSqlBuilder.PostgreSqlImage`, are marked `[Obsolete]`. They still compile, with a warning, and fall back to old images: `postgres:15.1` for PostgreSQL and a 2022 CU14 image for SQL Server. Passing the image yourself: - makes the PostgreSQL major version a visible, reviewed decision; - lets you match production, so a feature or behaviour of PostgreSQL 17 is tested on 17; - avoids `latest`, which would change under you between runs. ## SQL Server for comparison | | `PostgreSqlBuilder` | `MsSqlBuilder` | |---|---|---| | Package | `Testcontainers.PostgreSql` | `Testcontainers.MsSql` | | Container port | 5432 | 1433 | | Default database | `postgres` | `master` | | Default login | `postgres` / `postgres` | `sa` / `yourStrong(!)Password` | | Extra settings | durability off | `ACCEPT_EULA=Y` | | Connection string | `Host=...;Port=...` | `Server=host,port;...;TrustServerCertificate=True` | One difference in behaviour: the SQL Server image has no environment variable for creating a database, so when `WithDatabase` names one other than `master`, `MsSqlBuilder` runs a start-up callback that executes `CREATE DATABASE` once the server accepts connections. ## A minimal example ```csharp await using var db = new PostgreSqlBuilder("postgres:17").Build(); await db.StartAsync(); var options = new DbContextOptionsBuilder<OrdersDbContext>() .UseNpgsql(db.GetConnectionString()) .Options; ``` The `await using` disposes the container at the end of the scope; in a real suite a fixture owns it instead. ## Where the container lives in a suite The builder and container are plain objects, so ownership is a design choice rather than something Testcontainers decides: - a **test method** that owns the container pays the start-up cost on every test; - a **class fixture** starts one per test class, and xUnit runs different classes in parallel, so two classes mean two containers; - a **collection or assembly fixture** starts one for many classes, which is fastest but makes those tests share data and, in a collection, run one after another. Whichever owner you choose, the same rules hold: start before use, read the connection string from the container, and dispose when the owner is done. A test that only reads reference data can share freely; a test that writes needs the rows reset first.

  • Why does the PostgreSQL module turn fsync off?
    Test data does not need to survive a power cut, and `fsync=off`, `full_page_writes=off` and `synchronous_commit=off` remove the disk flushes that dominate small write transactions. The module passes them as server options at start. A test that is about crash recovery would need its own configuration, but an API suite only needs correct SQL behaviour, which these settings do not change.
  • Your build server runs Docker on another machine. What breaks if a test hard-codes localhost?
    The container's port is published on the Docker host, which is then not the machine running the tests. `GetConnectionString()` uses the container's `Hostname`, which Testcontainers resolves from the Docker endpoint, so it points at the right machine; a hard-coded `localhost` and `5432` points at nothing. Always take the address from the container.

  • Build() starts the container, so StartAsync() is optional.
  • The container always listens on localhost:5432, so the string can be hard-coded.
  • new PostgreSqlBuilder() without an image tracks the latest PostgreSQL release.
  • MsSqlBuilder logs in with Windows integrated security by default.
  • GetConnectionString() can be read before StartAsync() and stays valid afterwards.

Assumes Testcontainers 4.15 on .NET 10: the module builders' parameterless constructors and default-image constants are marked [Obsolete], so the image is passed explicitly.