Covers making a .NET test suite fast in CI: measuring where time goes, xUnit parallelism, sharding across agents, container reuse, test selection, and deciding what runs on every PR, on merge and nightly.
I'd start by measuring: per-test timings from the test reports usually show that a few slow tests, container start-ups and serial execution dominate.
Then I tier the suite: the PR gate runs fast, deterministic tests (unit plus API integration with shared containers) in under 10 minutes; the full integration and contract suite runs on merge; load tests, mutation testing and long E2E runs go nightly.
To make each tier fast: build once, cache NuGet and Docker images, run xUnit collections in parallel, start containers once per run and reset with Respawn, and shard across agents by timing. For big repos, test affected projects only on PRs.
The trade-off: some bugs are caught after merge instead of before, so main must stay releasable with quick reverts.
"First I'd measure rather than guess. I'd pull the TRX or JUnit results from the last few weeks of runs and sort tests by duration, and look at the pipeline timeline: restore, build, container start, test execution, publish. In my experience the time is rarely spread evenly: a handful of tests with
Task.Delayor polling, a container started per test class, and projects running one after another usually account for most of it.For example, at [company] our test stage hit [about 35 minutes]. The fixes, in order of payoff, were: build once and run
dotnet test --no-build; one SQL Server container per test run via an assembly-level fixture with Respawn between tests instead of a container per class, which alone saved [about 12 minutes]; making test collections safe to run in parallel by giving each collection its own database; replacing sleeps withFakeTimeProvider; and splitting the suite into [four] shards across agents, balanced by historical timings. The PR gate dropped to [about 8 minutes].Then I decide what runs where. Every PR: compile with warnings as errors, unit tests, API integration tests with real SQL Server, contract tests for anything other teams consume. On merge to main: the full suite, including slower integration paths, then deploy to a test environment and run smoke tests. Nightly: load tests with k6 or Azure Load Testing, Stryker.NET mutation runs, browser E2E. Flaky tests are quarantined out of the gate within a day, with an owner. The mistake I see is making the pipeline faster by deleting the integration tests, which just moves the cost to production. Fast feedback comes from structure, not from testing less."
| Cause | Typical cost | Fix |
|---|---|---|
| Rebuilding per test project | Minutes | Build once, dotnet test --no-build |
| Container per test class | 5–15 s each | Assembly or collection fixture; Respawn |
| Serial collections | Linear in test count | Isolated data, xUnit parallel collections |
| Sleeps and polling | Seconds per test | FakeTimeProvider, awaitable signals |
| No caching | 1–3 min restore and image pulls | NuGet cache, pre-pulled or cached images |
| One agent | Whole suite serial | Matrix or parallel jobs, timing-based sharding |
| Stage | Runs | Budget | Blocks |
|---|---|---|---|
| PR gate | Build, analysers, unit, API integration (containers), contract | < 10 min | Merge |
| On merge to main | Full suite, deploy to test env, smoke tests | < 20 min | Release |
| Nightly | Load, soak, Stryker.NET, browser E2E, dependency scans | Hours OK | Creates tickets |
| Pre-release | Smoke in staging (Australia East), synthetic checks | Minutes | Production deploy |
| Strategy | How | Trade-off |
|---|---|---|
| By project | Matrix job per test project | Simple; uneven if one project is huge |
| By timing | Split test list by historical duration | Balanced; needs timing data |
| Affected only | Run tests for projects changed (e.g. dotnet-affected) on PRs | Fast in monorepos; full run on main still needed |
After the changes, [our] PR gate went from [35] to [8] minutes across [4] shards, the merge stage ran the full [3,200] tests in [14] minutes, and the number of PRs per developer per week rose from [about 3] to [about 6] because nobody was batching changes any more.
Checks whether the candidate can design a test pipeline that balances speed, cost and confidence, starting from measurement.
Green flags
Red flags
restore ─▶ build ─▶ [start containers] ─▶ run tests ─▶ publish results
1-3m 2-5m 0.5-15m 5-25m <1m
Optimise the biggest box first. Test reports (--logger trx with VSTest, or the TRX/JUnit report extensions with Microsoft.Testing.Platform) give per-test durations; the CI timeline gives the rest.
xUnit groups tests into collections. By default each test class is its own collection, and collections run in parallel up to maxParallelThreads (default: number of logical processors). Tests inside one collection run serially.
Assembly
├─ Collection A (class 1) ── runs in parallel with ──┐
├─ Collection B (class 2) ── │
└─ Collection "db" (classes 3,4,5 share a DB) ── serial inside
So parallelism is only safe when collections don't share mutable state: static fields, one database, files, ports. Giving each collection its own database name on one SQL Server container keeps parallelism and isolation. Across test assemblies, dotnet test runs projects in parallel too.
A SQL Server container takes several seconds to start and needs ~2 GB of memory. Patterns, from cheapest to most isolated:
| Pattern | Starts | Isolation |
|---|---|---|
Assembly fixture (xUnit v3 AssemblyFixture) |
Once per assembly | Reset with Respawn |
| Collection fixture | Once per collection | Database per collection |
| Class fixture | Once per class | Strong, slow |
Testcontainers' reuse mode keeps containers between local runs, but it is meant for developer machines, not CI.
Split the test list into N roughly equal buckets by historical duration (greedy bin-packing), run each on its own agent, then merge results. GitHub Actions does this with a matrix and --filter; Azure Pipelines offers parallel jobs and test slicing in the VSTest task. More shards cost more agent minutes and more build overhead per shard, so beyond 4–8 the returns usually fall.
In large solutions, run tests only for changed projects and their dependants on PRs (build a project graph from ProjectReferences; tools like dotnet-affected do this). Always run everything on main to catch what selection missed.
A fast gate that is flaky is worse than a slow one. Track flake rate (tests that fail then pass on retry), quarantine with a tag or trait excluded from the gate, assign an owner, and fix or delete within a set period.
--filter and compare wall-clock time and total agent minutes.Task.Delay in a test with FakeTimeProvider.Advance and measure the gain.A sharded GitHub Actions workflow, plus xUnit configuration and traits used to tier the suite.
# .github/workflows/pr.yml
name: pr
on: pull_request
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with: { dotnet-version: '10.0.x', cache: true, cache-dependency-path: '**/packages.lock.json' }
- run: dotnet build -c Release -warnaserror
- uses: actions/upload-artifact@v4
with: { name: build, path: '**/bin/Release/**' }
test:
needs: build
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
shard: [Unit, Api, Data, Contracts] # balanced by historical timings
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with: { dotnet-version: '10.0.x' }
- uses: actions/download-artifact@v4
with: { name: build }
- run: docker pull mcr.microsoft.com/mssql/server:2022-latest # overlaps with restore on later steps
if: matrix.shard == 'Api' || matrix.shard == 'Data'
# Quarantined and nightly-only tests are excluded from the PR gate
- run: >
dotnet test -c Release --no-build
--filter "Shard=${{ matrix.shard }}&Category!=Quarantine&Category!=Nightly"
--logger trx --results-directory TestResults
- uses: actions/upload-artifact@v4
if: always()
with: { name: results-${{ matrix.shard }}, path: TestResults }
// xunit.runner.json in each test project
{
"parallelizeTestCollections": true,
"maxParallelThreads": "default"
}
#nullable enable
namespace Orders.Tests;
using Xunit;
// Traits drive the filters above; one convention for the whole solution
public sealed class PricingTests
{
[Fact, Trait("Shard", "Unit")]
public void Discount_Applies_From200() => Assert.Equal(180m, Pricing.Discount(200m));
[Fact, Trait("Shard", "Unit"), Trait("Category", "Nightly")]
public void Discount_PropertyBased_10kCases()
{
// Expensive exhaustive check: valuable, but not on every PR
for (var cents = 0; cents < 10_000; cents++)
{
var amount = cents / 100m * 50;
Assert.True(Pricing.Discount(amount) <= amount);
}
}
}
public static class Pricing
{
public static decimal Discount(decimal subtotal) => subtotal >= 200m ? subtotal * 0.9m : subtotal;
}
--no-build.The senior framing is that CI time is a product metric for the engineering team: it drives batch size, and batch size drives risk. Smaller, more frequent changes mean faster time to market, easier reviews, smaller blast radius and quicker rollback; that is the business case, and it lines up with the DORA metrics (deployment frequency, lead time for changes, change failure rate, time to restore) that leadership already understands. A 35-minute gate with 25 developers is also real money: roughly [25 × 3 runs a day × 25 minutes of waiting] is many engineer-hours a day spent context-switching.
I set an explicit budget (PR gate under 10 minutes, merge stage under 20) and treat breaches like performance regressions. I'm also explicit about what moves out of the gate: anything moved to post-merge needs main to be releasable, fast reverts and good alerting, otherwise you've just hidden the cost.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Shared containers + Respawn | Any suite using SQL Server or Redis | Fixture setup work | Tests that need different schemas |
| Parallel collections | Isolated tests | Upfront isolation work | Suites with shared static state you can't remove yet |
| Sharding across agents | Suites > ~10 min after other fixes | More agent minutes | Small suites: overhead dominates |
| Affected-only on PRs | Large monorepos | Selection tooling, misses indirect changes | Small solutions; never on main |
| Moving tests to nightly | Load, mutation, long E2E | Later feedback | Anything protecting correctness of common paths |
| Metric | Source | Why it matters |
|---|---|---|
| p50 / p90 PR gate duration | Pipeline analytics (Azure DevOps Analytics, GitHub Actions usage data) | Feedback speed, batch size |
| Flake rate | Test results with retry data; Azure DevOps flaky-test detection | Trust in red builds |
| Agent minutes per PR | Billing / usage reports | Cost of the strategy |
| Lead time and change failure rate | Deployment records | Business outcome |
I review these monthly so the improvement is visible and regressions get caught early.
Measure first. Collect TRX or JUnit reports from every CI run. A test that fails and then passes on the same commit is flaky. Rank tests by flaky rate.
Reproduce the failure: run the test in a loop (50 to 200 times), run it in parallel with its neighbours, run it on limited CPU, and use --blame-hang-timeout for hangs. The usual causes are time (DateTime.Now, Task.Delay waits), shared state, test order, parallelism, culture or time zone, and real network calls.
Quarantine visibly: tag the test so the release gate filters it out, but keep running and reporting it. Give it an owner, a ticket and a deadline, or delete it.
Prevent new ones with TimeProvider, banned-API analysers, the xUnit analysers and a flaky-rate dashboard. The trade-off is that quarantine unblocks releases but lowers coverage, so it must be temporary.
Wrap the resource in a fixture that implements IAsyncLifetime, so the container starts once in InitializeAsync and is removed in DisposeAsync. Then pick the sharing scope:
IClassFixture<T>: one instance per test class.ICollectionFixture<T> with [CollectionDefinition]: one instance for every class in the collection, and those classes run serially.[assembly: AssemblyFixture(typeof(T))]): one instance for the whole run, with tests still running in parallel, so the fixture must be thread-safe.Share the resource, not the state. Each test creates its own rows with unique keys, or you reset the database between tests with Respawn. Respawn is a small library that deletes data in foreign-key order and keeps the schema. The trade-off is that a wider scope gives a faster suite, but one test can leak data into another.
I'd start from the risks, not a pyramid: wrong money (pricing, payment), lost or duplicated orders, broken contracts with event consumers and the payment provider, and availability at peak. Then match each risk to the cheapest test that catches it. Unit tests for domain rules, integration tests for every endpoint and message handler using WebApplicationFactory, SQL Server in Testcontainers and a Service Bus emulator or fake, contract tests for published events and the payment API, a thin layer of smoke and E2E tests after each deployment, and load tests before launch. The merge gate is fast (under ~10 minutes); the release gate is smoke plus critical E2E on a staging slot. I judge it by escaped defects, change failure rate and feedback time. The trade-off is up-front effort in fixtures and contracts for much cheaper changes later.
How to tell it (STAR)
**S:** At [company] our PR test stage had grown to [35 minutes], so developers were batching changes and we'd had [two] incidents from big merges. **T:** I took on getting the PR gate under 10 minutes without dropping the integration tests. **A:** I ranked tests by duration from our TRX reports, then built once and reused the output, moved to a single SQL Server container with a database per collection and Respawn, replaced sleeps with FakeTimeProvider, enabled parallel collections and split the suite into [four] balanced shards. Slow load and mutation runs went nightly, and flaky tests got quarantined with owners. **R:** The PR gate dropped to [8 minutes], flaky runs fell from [8%] to [under 1%], and PRs per developer roughly [doubled] as people stopped batching.
Last updated 23 Nov 2026.