Testcontainers for .NET
Testcontainers for .NET starts real infrastructure — databases, message brokers, caches — as short-lived Docker containers for the duration of a test, then tears them down automatically.
Overview
Testcontainers for .NET provisions disposable infrastructure from test code so integration evidence runs against the same database, cache, broker, or service implementation used in production. A typed builder pins an image, configures credentials and wait strategy, starts the resource on a random mapped host port, and exposes the runtime connection string. Fixtures choose the lifecycle boundary: per test for maximum isolation, per class or collection for speed, or per assembly with careful reset. Schema migrations run after readiness, while transactions, schema-per-test, database-per-test, or tools such as Respawn restore known state. Tests must require a healthy Docker-compatible runtime, capture container logs on failure, bound startup and cleanup, and budget CPU, memory, disk, and parallelism in CI. Image tags and digests are supply-chain inputs that need review and vulnerability scanning. Testcontainers complements deterministic unit tests; it is valuable specifically where substitute behavior cannot prove SQL translation, constraints, transactions, network protocols, or broker semantics.
What you will learn
- Provision a pinned PostgreSQL container from xUnit.
- Inject a container-derived connection string.
- Choose fixture scope from isolation and cost.
- Create schema and reset state predictably.
- Operate container tests in parallel CI.
- Manage images, vulnerabilities, logs, and cleanup.
Prerequisites
- A running Docker-compatible engine and container fundamentals.
- xUnit fixtures and asynchronous lifecycle.
- Provider-specific client knowledge such as Npgsql.
When to use Testcontainers for .NET
Good fit
- Provider SQL, constraints, transactions, or protocol behavior matters.
- Tests need repeatable isolated infrastructure.
- CI provides a supported container runtime.
Choose another approach when
- Pure policy can be tested without infrastructure.
- The test cannot bound or clean resource use.
- An unavailable runtime is silently replaced by a fake.
Key concepts
The test uses the same engine and protocol semantics that production code depends on.
Module builders configure images, credentials, databases, wait strategies, and container behavior.
Per-test, class, collection, and assembly fixtures trade isolation for startup cost.
Random mapped ports and runtime connection strings allow safe parallel execution.
A container process start is not enough; tests wait for the service protocol to accept work.
Migrations or schema setup run against the live provider before controlled test data is inserted.
Transactions, truncation, Respawn, schemas, or databases restore isolation without accidental leakage.
Resource limits, image pulls, logs, cancellation, and the resource reaper make infrastructure tests operable.
Architecture
Test code starts named Docker containers, builds a WebApplicationFactory pointing at them, sends real HTTP requests, and asserts on responses backed by actual infrastructure.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The sample pins PostgreSQL, shares one container through an asynchronous xUnit fixture, creates schema after readiness, resets table state between tests, and verifies parameterized Npgsql behavior.
- 01Declare prerequisites
Require a supported Docker engine locally and in CI.
- 02Pin the image
Choose an explicit compatible tag or reviewed digest and scan it.
- 03Build the resource
Configure database, credentials, wait strategy, and resource limits.
- 04Start through a fixture
Select per-test or shared lifecycle and expose the dynamic connection string.
- 05Create schema
Run current migrations or deterministic schema setup after readiness.
- 06Reset state
Use the lightest reset that preserves provider semantics and parallel isolation.
- 07Capture and clean
Collect logs on failure, propagate cancellation, and always dispose resources.
Code example
A shared fixture starts a real PostgreSQL container once per test class, builds a WebApplicationFactory that runs EF Core migrations against it, and resets the database between tests.
using Testcontainers.PostgreSql;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
public sealed class OrdersApiFixture : IAsyncLifetime
{
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
.WithImage("postgres:16-alpine")
.WithDatabase("orders_test")
.WithUsername("test")
.WithPassword("test")
.Build();
public HttpClient Client { get; private set; } = default!;
private WebApplicationFactory<Program> _factory = default!;
public async Task InitializeAsync()
{
await _postgres.StartAsync();
_factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(host =>
host.ConfigureServices(services =>
{
services.RemoveAll<DbContextOptions<AppDbContext>>();
services.AddDbContext<AppDbContext>(opts =>
opts.UseNpgsql(_postgres.GetConnectionString()));
}));
// Run migrations against the real container
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
Client = _factory.CreateClient();
}
public async Task DisposeAsync()
{
await _factory.DisposeAsync();
await _postgres.DisposeAsync();
}
}
public sealed class PlaceOrderTests(OrdersApiFixture fixture)
: IClassFixture<OrdersApiFixture>
{
[Fact]
public async Task PlaceOrder_returns_201_and_persists_to_database()
{
var response = await fixture.Client.PostAsJsonAsync("/api/orders",
new { CustomerId = Guid.NewGuid(), Lines = new[] { new { ProductId = Guid.NewGuid(), Quantity = 2 } } });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
var orderId = body.GetProperty("id").GetGuid();
Assert.NotEqual(Guid.Empty, orderId);
}
}Testing strategy
Container tests prove the integration setup as well as application behavior.
- Assert the image is explicitly pinned.
- Run real constraint and transaction cases.
- Verify dynamic connection injection.
- Run tests concurrently to detect collisions.
- Cancel startup and confirm cleanup.
- Prove migrations work from an empty database.
Security considerations
Test containers still execute third-party images and handle credentials.
- Use reviewed official images.
- Scan packages and images.
- Use test-only credentials.
- Do not expose ports beyond the host.
- Protect Docker socket access.
Performance and scalability
Reuse infrastructure only where state can be reset safely.
- Share a container per class or collection.
- Pull images before timed CI lanes.
- Limit parallel container count.
- Use lightweight reset instead of restart.
- Track startup, test, and cleanup duration.
Deployment and operations
CI runners need predictable container capabilities and resource budgets.
- Document required runtime and architecture.
- Pre-pull or cache pinned images.
- Set CPU, memory, disk, and timeout limits.
- Publish logs on failure.
- Clean orphaned resources after cancellation.
Common problems and fixes
Docker unavailable.
Likely cause: The engine is stopped or endpoint is inaccessible.
Fix: Verify engine responsiveness and runner permissions before tests.
Container starts but tests cannot connect.
Likely cause: The service is not ready or a fixed port was assumed.
Fix: Use the module wait strategy and runtime connection string.
Parallel tests corrupt data.
Likely cause: Fixtures share state without reset.
Fix: Use isolated databases or serialize and reset explicitly.
CI disk fills.
Likely cause: Images and stopped resources accumulate.
Fix: Apply cleanup policy, caching limits, and resource reaping.
Tests changed after image pull.
Likely cause: A floating tag resolved differently.
Fix: Pin a version or digest and update deliberately.
Cleanup hangs.
Likely cause: Cancellation or disposal is missing.
Fix: Bound lifecycle calls and dispose fixtures in finally paths.
Best practices
- Use the real provider.
- Pin images explicitly.
- Use dynamic mapped ports.
- Wait for protocol readiness.
- Share only with safe reset.
- Bound CI resources.
- Capture failure logs.
- Dispose every resource.
Production checklist
- Docker prerequisites are documented.
- Images are pinned and scanned.
- Fixture scope is justified.
- Endpoints come from the running container.
- Schema starts from current migrations.
- Data reset preserves isolation.
- CI resources and timeouts are bounded.
- Logs and cleanup work after failure.
Common interview questions
Why not use an in-memory database?
It cannot prove provider SQL translation, constraints, locking, transactions, or wire behavior.
How are port conflicts avoided?
Testcontainers maps the container port to a random available host port and exposes it after startup.
What fixture scope should you use?
The narrowest scope affordable for startup cost, with an explicit reset strategy when sharing.
How do you reset PostgreSQL state?
Use rollback, truncation, Respawn, isolated schemas, or databases according to the behavior under test.
Why pin an image?
Floating tags can change engine behavior and supply-chain contents without a code review.
What does a wait strategy solve?
It waits for actual service readiness instead of treating process start as usable infrastructure.
What must CI provide?
A supported container runtime, image access, sufficient resources, bounded parallelism, cleanup, and diagnostic artifacts.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Testcontainers PostgreSQL Inventory
A .NET 10 integration lab provisioning pinned PostgreSQL with Testcontainers, dynamic endpoints, schema setup, state reset, Npgsql, and real provider tests.
- Run
dotnet run --project src/TestcontainersPostgresInventory- Test
dotnet test TestcontainersPostgresInventory.slnx