TExcelTAD
Home › ASP.NET Core › Testing

Testing

ASP.NET Core was designed to be tested. Because services arrive through dependency injection and the whole app can be hosted in memory, you can test at three levels:

Level What runs Speed Tools
Unit tests one class or function, dependencies replaced by fakes milliseconds xUnit / NUnit / MSTest, fakes or Moq/NSubstitute
Integration tests the real app pipeline (routing, middleware, DI, JSON) on an in-memory server fast WebApplicationFactory<Program> from Microsoft.AspNetCore.Mvc.Testing
End-to-end tests a deployed app driven through a browser slow Playwright, Selenium

Most of your tests should be fast unit and integration tests.

Setting up a test project

bash
$ dotnet new xunit -o tests/NotesApi.Tests
$ dotnet add tests/NotesApi.Tests reference src/NotesApi
$ dotnet add tests/NotesApi.Tests package Microsoft.AspNetCore.Mvc.Testing

WebApplicationFactory<TEntryPoint> needs a public type from your app. With top-level statements in .NET 9 the generated Program class is internal, so add one line to the end of Program.cs:

csharp
public partial class Program { }

Unit testing a service

Keep business logic in plain classes that take their dependencies through the constructor. Then a test is just C#:

csharp
public class DiscountServiceTests
{
    [Theory]
    [InlineData(50, 0)]
    [InlineData(100, 10)]
    [InlineData(250, 25)]
    public void Discount_is_ten_percent_from_100(decimal total, decimal expected)
    {
        var service = new DiscountService();
        Assert.Equal(expected, service.DiscountFor(total));
    }
}

The same idea without a test framework — arrange, act, assert — runs right here:

csharp · try it yourself
using System;
using System.Collections.Generic;

int passed = 0, failed = 0;
void AssertEqual<T>(T expected, T actual, string name)
{
    bool ok = EqualityComparer<T>.Default.Equals(expected, actual);
    if (ok) passed++; else failed++;
    Console.WriteLine(
quot;{(ok ? "PASS" : "FAIL")} {name}{(ok ? "" :
quot; (expected {expected}, got {actual})")}"); } // Arrange: a fake repository instead of a database var repo = new FakeNoteRepository(); var service = new NoteService(repo); // Act + Assert var created = service.Create(" Buy milk "); AssertEqual("Buy milk", created.Text, "Create trims text"); AssertEqual(1, repo.Saved.Count, "Create saves exactly one note"); try { service.Create(" "); failed++; Console.WriteLine("FAIL Empty text throws"); } catch (ArgumentException) { passed++; Console.WriteLine("PASS Empty text throws"); } AssertEqual(2, service.Create("Call Bob").Id, "Ids increase"); Console.WriteLine(
quot;Passed: {passed}, Failed: {failed}"); record Note(int Id, string Text); interface INoteRepository { Note Add(string text); } class FakeNoteRepository : INoteRepository { public List<Note> Saved { get; } = new(); public Note Add(string text) { var n = new Note(Saved.Count + 1, text); Saved.Add(n); return n; } } class NoteService(INoteRepository repo) { public Note Create(string text) { if (string.IsNullOrWhiteSpace(text)) throw new ArgumentException("Text is required."); return repo.Add(text.Trim()); } }
PASS Create trims text
PASS Create saves exactly one note
PASS Empty text throws
PASS Ids increase
Passed: 4, Failed: 0

Integration tests with WebApplicationFactory

WebApplicationFactory<Program> starts your real app on an in-memory TestServer — no network port — and hands you an HttpClient wired to it. Every request goes through the full pipeline: middleware, routing, model binding, filters, JSON serialization.

csharp
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;

public class NotesApiTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task Get_notes_returns_ok_and_json()
    {
        var client = factory.CreateClient();

        var response = await client.GetAsync("/notes");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
    }

    [Fact]
    public async Task Post_note_returns_created_with_location()
    {
        var client = factory.CreateClient();

        var response = await client.PostAsJsonAsync("/notes", new { text = "Test note" });

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        var note = await response.Content.ReadFromJsonAsync<NoteDto>();
        Assert.Equal("Test note", note!.Text);
        Assert.Equal(
quot;/notes/{note.Id}", response.Headers.Location?.ToString()); } [Fact] public async Task Post_empty_note_returns_validation_problem() { var client = factory.CreateClient(); var response = await client.PostAsJsonAsync("/notes", new { text = "" }); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } } public record NoteDto(int Id, string Text);

IClassFixture makes xUnit create the factory once and share it across the tests in the class, so the app starts only once.

Replacing services in tests

Override registrations with WithWebHostBuilder and ConfigureTestServices. Typical swaps: an in-memory or SQLite database, a fake clock, a fake e-mail sender, a test authentication handler.

csharp
public class CustomFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("Testing");
        builder.ConfigureTestServices(services =>
        {
            services.RemoveAll<IEmailSender>();
            services.AddSingleton<IEmailSender, FakeEmailSender>();
            services.AddSingleton<TimeProvider>(new FakeTimeProvider(
                new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)));
        });
    }
}

Tip: FakeTimeProvider (package Microsoft.Extensions.TimeProvider.Testing) lets you move time forward in tests. Inject TimeProvider instead of calling DateTime.UtcNow in your code.

Running the tests

bash · try it yourself
$ dotnet test
Restore complete (0.7s)
  NotesApi succeeded (1.9s) → src/NotesApi/bin/Debug/net9.0/NotesApi.dll
  NotesApi.Tests succeeded (1.1s) → tests/NotesApi.Tests/bin/Debug/net9.0/NotesApi.Tests.dll
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 9.0.0)
[xUnit.net 00:00:00.12]   Discovering: NotesApi.Tests
[xUnit.net 00:00:00.18]   Discovered:  NotesApi.Tests
[xUnit.net 00:00:00.19]   Starting:    NotesApi.Tests
[xUnit.net 00:00:01.04]   Finished:    NotesApi.Tests
  NotesApi.Tests test succeeded (2.3s)

Test summary: total: 6, failed: 0, succeeded: 6, skipped: 0, duration: 2.3s
Build succeeded in 6.4s

When a test fails, the summary lists it with the assertion message:

bash · try it yourself
$ dotnet test --filter "FullyQualifiedName~Post_note"
Restore complete (0.6s)
  NotesApi succeeded (0.4s) → src/NotesApi/bin/Debug/net9.0/NotesApi.dll
  NotesApi.Tests test failed with 1 error(s) (1.8s)
    /home/dev/NotesApi/tests/NotesApi.Tests/NotesApiTests.cs(28): error TESTERROR:
      NotesApiTests.Post_note_returns_created_with_location (112ms): Error Message: Assert.Equal() Failure: Values differ
      Expected: Created
      Actual:   OK

Test summary: total: 1, failed: 1, succeeded: 0, skipped: 0, duration: 1.8s
Build failed with 1 error(s) in 3.2s

Here the endpoint returned Results.Ok(note) instead of Results.Created(

quot;/notes/{note.Id}", note) — exactly the kind of contract bug integration tests catch.

What an integration test really does

Conceptually, the TestServer feeds a request straight into your pipeline delegate and captures the response, with no sockets in between. A tiny model of that:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Text.Json;

// "The app": a route table of handlers
var notes = new List<string> { "Buy milk" };
var routes = new Dictionary<string, Func<string?, (int Status, string Body)>>
{
    ["GET /notes"] = _ => (200, JsonSerializer.Serialize(notes)),
    ["POST /notes"] = body =>
    {
        var text = JsonDocument.Parse(body!).RootElement.GetProperty("text").GetString();
        if (string.IsNullOrEmpty(text)) return (400, "{\"title\":\"Text is required\"}");
        notes.Add(text);
        return (201, JsonSerializer.Serialize(new { id = notes.Count, text }));
    },
};

// "The TestServer": calls the pipeline in memory
(int, string) Send(string method, string path, string? body = null) =>
    routes.TryGetValue(
quot;{method} {path}", out var handler) ? handler(body) : (404, ""); foreach (var (method, path, body) in new (string, string, string?)[] { ("GET", "/notes", null), ("POST", "/notes", "{\"text\":\"Write tests\"}"), ("POST", "/notes", "{\"text\":\"\"}"), ("GET", "/missing", null), }) { var (status, response) = Send(method, path, body); Console.WriteLine(
quot;{method,-4} {path,-8} -> {status} {response}".TrimEnd()); }
GET  /notes   -> 200 ["Buy milk"]
POST /notes   -> 201 {"id":2,"text":"Write tests"}
POST /notes   -> 400 {"title":"Text is required"}
GET  /missing -> 404

Test yourself

What does WebApplicationFactory<Program> give your tests?

  1. A mock HttpContext only
  2. Your real app running on an in-memory TestServer plus an HttpClient
  3. A browser automation driver
  4. A copy of production data

Why add public partial class Program { } in a .NET 9 app with top-level statements?

  1. To make the generated Program class public so the test project can reference it
  2. To speed up startup
  3. To enable minimal APIs
  4. It is required by Kestrel

Which method replaces a registered service with a fake in an integration test?

  1. UseTestServer
  2. MapFallback
  3. AddControllers
  4. ConfigureTestServices