Experienced developers write unit tests as an integral part of the development process. They make sure that classes work as expected and help keep components working during refactoring and further development. Integration tests combine multiple components to verify that larger parts of the code work together. End-to-End tests go one step further and prove that the whole application works: from the UI and user input, through routing, middleware, processing, dependency injection and persistence in the database, to the expected page or API response.
This article shows a setup I use on a mid-sized ASP.NET Core website with around 60 test fixtures. It boils down to three ingredients:
- A real SQL Server in a throw-away Docker container, started by Testcontainers.
- The real web host, running in memory through WebApplicationFactory<Program>.
- Real HTML, parsed with AngleSharp so that tests assert on elements rather than strings.
No mocks of the database, no in-memory EF provider, no browser. Each test sends an HTTP request and checks what a user would get back. That is why I call them End-to-End tests rather than integration tests.
The examples use NUnit, but the same approach works with xUnit or MSTest.
Where we are heading: one complete test
Here is the kind of test this article builds up to. It writes a row into a real SQL Server, requests a page from the real application and checks the HTML a visitor would get:
[TestFixture, Category("EndToEnd")]
public sealed class ReviewPageTests
{
[SetUp]
public Task ResetAsync() => DatabaseResetter.ResetAsync();
[Test]
public async Task Get_APublishedReview_ShowsTheTitleAndBothVerdicts()
{
// Arrange: save a review straight into SQL Server running in Docker
await using (var db = SqlServerTestDatabase.CreateContext())
{
db.Reviews.Add(TestEntities.PublishedReview(slug: "acme-studio-3", title: "Acme Studio 3 on test"));
await db.SaveChangesAsync();
}
// Act: request the page from the in-memory web host
using var client = EndToEndTestHost.Factory.CreateClient();
using var response = await client.GetAsync("/en/reviews/acme-studio-3");
// Assert: parse the HTML and check what a visitor sees
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var page = await response.ReadAsHtmlDocumentAsync();
Assert.Multiple(() =>
{
Assert.That(page.QuerySelector("h1")?.TextContent.Trim(), Is.EqualTo("Acme Studio 3 on test"));
Assert.That(page.QuerySelectorAll(".verdict"), Has.Length.EqualTo(2));
Assert.That(page.QuerySelector("link[rel=canonical]")?.GetAttribute("href"),
Does.EndWith("/en/reviews/acme-studio-3"));
});
}
}It reads like a plain unit test, but every line goes through the real stack: routing, middleware, DI, EF Core, Razor and SQL Server.
Before you start: preparing your machine
You need Docker and the .NET SDK, nothing else. SQL Server does not have to be installed: Testcontainers pulls the SQL Server image and runs it in a container for you. On a clean Windows machine, the setup takes about 15 minutes and one or two restarts.
Windows 10/11 from scratch
Check that virtualization is on. Open Task Manager → Performance → CPU and look for Virtualization: Enabled. If it says disabled, switch on Intel VT-x or AMD-V in the BIOS/UEFI settings.
Install WSL 2. Docker Desktop runs Linux containers on top of it. In PowerShell as administrator:
wsl --installRestart when asked. If WSL is already installed, wsl --update brings it up to date.
Install Docker Desktop, either from docker.com or with winget:
winget install -e --id Docker.DockerDesktopIn the installer, keep Use WSL 2 instead of Hyper-V checked. Log out and back in afterwards.
Start Docker Desktop and wait until it says the engine is running. Make sure it uses Linux containers: if the tray menu offers Switch to Windows containers…, you are in the right mode. The SQL Server image only exists for Linux.
Verify Docker works:
docker version
docker run --rm hello-worldInstall the .NET 10 SDK and check it:
winget install Microsoft.DotNet.SDK.10
dotnet --list-sdksOptional: pre-pull the SQL Server image. It is about 1.5 GB, so the first test run would otherwise spend minutes downloading it:
docker pull mcr.microsoft.com/mssql/server:2022-latestRun the tests (only with Category “EndToEnd”):
dotnet test --filter TestCategory=EndToEnd
SQL Server in a Docker container
To run the SQL database, I use the Testcontainers.MsSql NuGet package (see dotnet.testcontainers.org). One container serves the whole test run. Starting SQL Server takes 10–20 seconds, so you pay that once, not per fixture. Use the same image your team runs locally in docker-compose.yml, so tests cannot pass on a server version nobody else uses.
internal static class SqlServerTestDatabase
{
private const string Image = "mcr.microsoft.com/mssql/server:2022-latest";
private static MsSqlContainer? _container;
public static string ConnectionString { get; private set; } = null!;
public static async Task StartAsync()
{
_container = new MsSqlBuilder(Image).Build();
await _container.StartAsync();
// The container hands out a connection string for master;
// we want our own database, which Migrate() creates.
ConnectionString = new SqlConnectionStringBuilder(_container.GetConnectionString())
{
InitialCatalog = "MyApp",
}.ConnectionString;
await using var context = CreateContext();
await context.Database.MigrateAsync();
}
public static async Task StopAsync()
{
if (_container is not null) await _container.DisposeAsync();
}
public static MyDbContext CreateContext() =>
new(new DbContextOptionsBuilder<MyDbContext>().UseSqlServer(ConnectionString).Options);
}Two details matter here. First, run the real EF Core migrations, not EnsureCreated(): that way the tests check the same schema a deployment produces. Second, keep CreateContext() public, because some tests need to write rows directly or read back what a request saved.
Resetting data between tests with Respawn
Tests that write must start from a clean database. Dropping and re-migrating is slow, so I use the Respawn NuGet package (see github.com/jbogard/Respawn), which reads the schema once and then deletes all rows in foreign-key order.
_respawner = await Respawner.CreateAsync(connection, new RespawnerOptions
{
DbAdapter = DbAdapter.SqlServer,
// Migration history is schema, not test data.
TablesToIgnore = [new Table("__EFMigrationsHistory")],
});
// later, in [SetUp] of a fixture that writes:
await _respawner.ResetAsync(connection);A useful rule: read-only fixtures share seeded data; writing fixtures reset it. Read-only tests stay fast, and tests that write never see leftover data.
The web host with WebApplicationFactory
The key part of this setup is WebApplicationFactory<TEntryPoint> from Microsoft.AspNetCore.Mvc.Testing. This native .NET component makes end-to-end testing possible. It creates an in-memory instance of the application and offers a method to create an HttpClient for sending requests to it.
WebApplicationFactory<Program> boots your real Program.cs on an in-memory TestServer. No port, no Kestrel, but the full middleware pipeline. Subclass it to set the test configuration in one place:
public sealed class MyAppFactory : WebApplicationFactory<Program>
{
public static readonly DateTimeOffset FixedUtcNow = new(2026, 10, 1, 10, 0, 0, TimeSpan.Zero);
private readonly IReadOnlyDictionary<string, string?> _overrides;
private readonly string _environment;
public MyAppFactory(
IReadOnlyDictionary<string, string?>? overrides = null,
string environmentName = "Testing")
{
_overrides = overrides ?? new Dictionary<string, string?>();
_environment = environmentName;
}
public FakeTimeProvider FakeTime { get; } = new(FixedUtcNow);
public HttpClient CreateClientWithoutRedirects() =>
CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment(_environment);
builder.ConfigureAppConfiguration((_, config) =>
{
config.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:Default"] = SqlServerTestDatabase.ConnectionString,
["Sentry:Dsn"] = "", // no telemetry from tests
["Ads:Enabled"] = "false", // no third-party scripts
});
config.AddInMemoryCollection(_overrides); // applied last, wins
});
builder.ConfigureTestServices(services =>
{
services.Replace(ServiceDescriptor.Singleton<TimeProvider>(FakeTime));
});
}
}What each piece buys you:
- Testing environment keeps development-only middleware and production-only features (HSTS, for example) out of the way.
- The connection string is read when the host is built, after the container is up. That is why it cannot be a static default value.
- Configuration overrides in the constructor let one fixture spin up a second host with a feature switched on (a cookie banner, a canonical host redirect) without touching the shared host.
- FakeTimeProvider replaces the system clock. If the app injects TimeProvider instead of calling DateTime.UtcNow, every rendered date and computed age is stable, and a test can call FakeTime.Advance(...) instead of waiting.
- CreateClientWithoutRedirects() lets you assert on the 301 itself rather than on the page it redirects to.
Starting everything once
In NUnit, a [SetUpFixture] in the root namespace runs once before all tests in the assembly. That is the place to start the container, the resetter and the shared host:
[SetUpFixture]
public sealed class EndToEndTestHost
{
public static MyAppFactory Factory { get; private set; } = null!;
[OneTimeSetUp]
public async Task StartAsync()
{
await SqlServerTestDatabase.StartAsync(); // Start SQL Server
await DatabaseResetter.InitializeAsync(); // Prepare the database resetter
Factory = new MyAppFactory(); // Our WebApplicationFactory
await SeededDatabase.EnsureSeededAsync(); // Seed the shared test data
}
[OneTimeTearDown]
public async Task StopAsync()
{
await Factory.DisposeAsync();
await SqlServerTestDatabase.StopAsync();
}
}
Reading pages
Asserting with Does.Contain("<h1>Hello</h1>") breaks on every whitespace or attribute change. Parse the HTML instead and query it with CSS selectors, exactly as a browser does. One extension method is enough:
internal static class HttpResponseMessageExtensions
{
public static async Task<IHtmlDocument> ReadAsHtmlDocumentAsync(this HttpResponseMessage response)
{
var html = await response.Content.ReadAsStringAsync();
return await new HtmlParser().ParseDocumentAsync(html);
}
}Then, inside each fixture, add a small helper that fetches a page and fails fast on a wrong status code:
private static async Task<IHtmlDocument> GetPageAsync(string url)
{
using var client = EndToEndTestHost.Factory.CreateClientWithoutRedirects();
using var response = await client.GetAsync(new Uri(url, UriKind.Relative));
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
return await response.ReadAsHtmlDocumentAsync();
}
private static string Text(IHtmlDocument doc, string selector) =>
doc.QuerySelector(selector)?.TextContent.Trim() ?? string.Empty;Now a test reads like a description of the page:
using var page = await GetPageAsync("/en/authors/john");
Assert.That(page.QuerySelectorAll("h1"), Has.Length.EqualTo(1));
Assert.That(Text(page, ".author__name"), Is.EqualTo("John Marlow"));
Assert.That(page.QuerySelector("link[rel=canonical]")?.GetAttribute("href"),
Does.EndWith("/en/authors/john"));Not everything is HTML. Headers, status codes and redirects come straight from HttpResponseMessage; JSON endpoints use ReadFromJsonAsync<T>(). For a request with special headers (a language, an API key), build an HttpRequestMessage and call SendAsync:
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri("/test/throw", UriKind.Relative));
request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("de-DE"));
using var response = await client.SendAsync(request);
Composing tests
With the plumbing in place, fixtures fall into three patterns.
Pattern A: read-only page tests on seeded data
The most common kind. Seed once, never reset, assert on what the page shows. Name tests after the behavior a visitor sees:
[TestFixture, Category("EndToEnd")]
public sealed class AuthorPageTests
{
[OneTimeSetUp]
public Task SeedAsync() => SeededDatabase.EnsureSeededAsync();
[Test]
public async Task Get_AnAuthorPage_ShowsTheNameAndTheAge()
{
using var page = await GetPageAsync("/en/authors/john");
Assert.Multiple(() =>
{
Assert.That(Text(page, ".author__name"), Is.EqualTo("John Marlow"));
// Born 12 April 1988, clock fixed at 1 October 2026.
Assert.That(Text(page, ".author__age"), Is.EqualTo("38 years old"));
});
}
}Note the age: it is written out as a constant, not computed in the test. If the test and the app computed it the same way, they could share the same bug.
Pattern B: tests with write
Reset in [SetUp], arrange rows through the DbContext or through the API, act, then read back with a fresh context:
[SetUp]
public Task ResetAsync() => DatabaseResetter.ResetAsync();
[Test]
public async Task SaveChanges_ForAReviewWithItsWholeGraph_ReadsBackEveryPart()
{
var reviewId = await SaveReviewAsync(); // arrange + act
await using var context = SqlServerTestDatabase.CreateContext();
var review = await context.Reviews
.AsNoTracking()
.Include(r => r.Translations)
.SingleAsync(r => r.Id == reviewId);
Assert.That(review.Translations.Single().Title, Is.EqualTo("Acme Studio 3 on test"));
}A fresh context matters: reading through the context that saved the entity returns it from the change tracker and proves nothing about the database. These tests catch real SQL Server issues that an in-memory provider never would: column lengths, unique indexes, cascade deletes, decimal precision.
Pattern C: a dedicated host for one scenario
Some behavior only appears with a different configuration or environment. Create a second factory in the fixture and dispose of it afterwards:
private MyAppFactory _production = null!;
[OneTimeSetUp]
public void Start() => _production = new MyAppFactory(environmentName: "Production");
[OneTimeTearDown]
public ValueTask Stop() => _production.DisposeAsync();
[Test]
public async Task Get_InProduction_SendsHsts()
{
using var client = _production.CreateClient(new() { BaseAddress = new Uri("https://localhost") });
using var response = await client.GetAsync("/en");
Assert.That(response.Headers.Contains("Strict-Transport-Security"), Is.True);
}Both hosts share the same database container, so the only extra cost is booting the second host.
Conclusion
Most projects use unit tests for isolated components and integration tests for combined use cases. Your CI/CD pipeline can also run full End-to-End tests to make sure the application behaves as expected.
What can be tested? Among other things: complex UI elements, routing, database migrations, caching, REST API responses, model binding, paging and middleware layers.
End-to-End tests for an ASP.NET Core application need surprisingly little code once the right pieces are in place. The two key ones are:
- Testcontainers starts a real SQL Server in Docker for each test run and throws it away afterwards. No local installation, no shared test database.
- WebApplicationFactory hosts the real Program.cs in memory, with the full middleware pipeline and a test configuration on top.
Two more packages keep the tests fast to write and fast to run:
- Respawn wipes the data between tests that write, in milliseconds, without touching the schema.
- AngleSharp parses the returned HTML, so tests assert on elements and CSS selectors instead of raw strings.
Where this fits at SABO IT
The tests in this article verify the user interface where verification is cheapest: in the pipeline, before anything is deployed. The same question returns later, on the finished device, which a pipeline cannot reach. That is the layer our testing service covers: with SABOtap, a robot operates the control panel and image analysis checks the response. It runs on production firmware and needs no test interface on the device. SABOtap complements your unit, integration and HIL tests by covering the layer your customers actually use: the user interface of the finished device.
SABO IT develops industrial software with more than 60 IT experts at five locations in Germany and the Czech Republic. We have been developing software since 1983 and have operated as SABO IT since 2012.

Luboš is an experienced .NET developer (web and mobile apps) very familiar with SQL and DevOps. He developed a lot of web applications used worldwide by industry and the academical world. He holds a bachelor’s degree in applied physics and astrophysics. Likes bowling, rides e-mountainbike, skis and plays the violin.





SABO IT
More articles




