Kiểm thử Tích hợp với WebApplicationFactory: Đảm Bảo Ứng Dụng ASP.NET Core Chạy Đúng Như Mong Đợi (Lộ Trình .NET)

Một bài kiểm thử gọi controller với service đã mock, rồi mock luôn cả DbContext, thường chỉ chứng minh rằng mock hoạt động. Giá trị thật của kiểm thử tích hợp nằm ở chỗ khác: middleware, model binding, authentication, serialization, EF Core và transaction chạy cùng nhau trên một request thật. WebApplicationFactory cho bạn đúng thứ đó mà không cần mở socket hay chạy IIS.

Cập nhật 2026

  • .NET 10 sinh sẵn public partial class Program cho top-level statements. Bạn không còn phải thêm dòng public partial class Program { } ở cuối Program.cs như hướng dẫn của .NET 8/9.
  • Microsoft.AspNetCore.Mvc.Testing 10.0.14 đi cùng ASP.NET Core 10; dotnet test chạy trên Microsoft.Testing.Platform (MTP).
  • EF Core InMemory không còn là mặc định cho kiểm thử tích hợp. Nó không có constraint, transaction hay SQL thật. Stack hiện tại là Testcontainers 4.16 + Respawn 7.0 với database thật trong container.
  • .NET 8 và .NET 9 hết hỗ trợ ngày 2026-11-10. Nếu test project còn target hai framework này, đó là việc phải sửa trước khi bàn tới chuyện test.

WebApplicationFactory thực chất làm gì

Nó đọc entry point của ứng dụng, dựng lại host trong tiến trình test, thay Kestrel bằng TestServer, rồi đưa bạn một HttpClient nói chuyện với TestServer qua handler in-memory. Request vẫn đi qua toàn bộ pipeline: routing, middleware, filter, controller, EF Core. Chỉ có network và cổng TCP là biến mất.

Hai hệ quả thực tế. Thứ nhất, test nhanh hơn E2E và không cần port. Thứ hai, những gì phụ thuộc vào socket thật — HTTPS redirect, HTTP/2, giới hạn kích thước request của Kestrel — không kiểm thử được ở đây. Đừng viết test khẳng định UseHttpsRedirection trả 307: TestServer không có cổng HTTPS để redirect, middleware chỉ ghi warning rồi cho request đi tiếp.

Dựng factory: thay service, không thay pipeline

Project test cần tham chiếu project web và bộ package dưới đây. xunit.v3 là dòng package riêng; đừng trộn với xunit 2.x.

<!-- File: Tests/Tests.csproj -->
<PropertyGroup>
  <TargetFramework>net10.0</TargetFramework>
  <OutputType>Exe</OutputType>
  <IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
  <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
  <PackageReference Include="Testcontainers.PostgreSql" Version="4.16.0" />
  <PackageReference Include="Respawn" Version="7.0.0" />
  <PackageReference Include="xunit.v3" Version="4.0.2" />
</ItemGroup>

Điểm quan trọng nhất trong toàn bài: dùng ConfigureTestServices, không phải ConfigureServices. ConfigureTestServices được đảm bảo chạy sau khi ứng dụng đăng ký xong service của nó, nên RemoveAll mới có tác dụng. ConfigureServices trên IWebHostBuilder không có thứ tự đảm bảo đó và là nguồn gốc của rất nhiều test “không hiểu sao vẫn dùng DB cũ”.

// File: Tests/Infrastructure/ApiFactory.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection.Extensions;

public sealed class ApiFactory(string connectionString) : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("Testing");

        builder.ConfigureTestServices(services =>
        {
            // EF Core 9+ đăng ký thêm IDbContextOptionsConfiguration.
            // Chỉ xóa DbContextOptions là chưa đủ.
            services.RemoveAll<DbContextOptions<AppDbContext>>();
            services.RemoveAll<IDbContextOptionsConfiguration<AppDbContext>>();

            services.AddDbContext<AppDbContext>(options =>
                options.UseNpgsql(connectionString));

            services.RemoveAll<IEmailSender>();
            services.AddSingleton<IEmailSender, RecordingEmailSender>();
        });
    }
}

Program ở đây là type do SDK sinh. Nếu solution của bạn còn target .NET 8/9, thêm public partial class Program { } vào cuối Program.cs; trên .NET 10 không cần, vì SDK đã sinh khai báo đó.

HttpClient mà CreateClient trả về

Mặc định CreateClient() trả về client có BaseAddress là http://localhost, tự động theo redirect (tối đa 7 lần) và quản lý cookie. Không có request nào ra khỏi tiến trình. Nếu test của bạn cần khẳng định một redirect, tắt auto-redirect và tự đọc Location:

var client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
    AllowAutoRedirect = false,
    BaseAddress = new Uri("http://localhost"),
    HandleCookies = true
});

Cookie được giữ trong một CookieContainer gắn với client đó, nên luồng “đăng nhập rồi gọi endpoint bảo vệ” hoạt động tự nhiên. Nhưng đừng dùng chung một client giữa các test: state cookie sẽ rò rỉ. Tạo client mới trong mỗi test, hoặc mỗi lần assert một user khác.

Test đầu tiên: status, body, ProblemDetails

Một test tích hợp tốt khẳng định hợp đồng HTTP, không khẳng định implementation. Dưới đây là case tạo đơn hàng và case dữ liệu sai:

// File: Tests/Orders/CreateOrderTests.cs
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc;

[Collection("postgres")]
public sealed class CreateOrderTests(PostgresFixture db) : IAsyncLifetime
{
    private ApiFactory _factory = null!;

    public async ValueTask InitializeAsync()
    {
        await db.ResetAsync();
        _factory = new ApiFactory(db.ConnectionString);
    }

    public ValueTask DisposeAsync()
    {
        _factory.Dispose();
        return ValueTask.CompletedTask;
    }

    [Fact]
    public async Task Post_ValidOrder_Returns201WithLocation()
    {
        var client = _factory.CreateClient();
        var response = await client.PostAsJsonAsync("/api/orders", new
        {
            customerId = Guid.NewGuid(),
            items = new[] { new { sku = "SKU-1", quantity = 2 } }
        });

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        Assert.NotNull(response.Headers.Location);

        var created = await response.Content.ReadFromJsonAsync<OrderResponse>();
        Assert.Equal("Pending", created!.Status);
    }

    [Fact]
    public async Task Post_EmptyItems_ReturnsValidationProblem()
    {
        var client = _factory.CreateClient();
        var response = await client.PostAsJsonAsync("/api/orders", new
        {
            customerId = Guid.NewGuid(),
            items = Array.Empty<object>()
        });

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);

        var problem = await response.Content.ReadFromJsonAsync<ValidationProblemDetails>();
        Assert.Contains("items", problem!.Errors.Keys);
    }
}

ValidationProblemDetails là kiểu mà [ApiController] và validation của Minimal API trả về trong ASP.NET Core 10. Đọc nó thay vì so sánh chuỗi JSON: test sẽ không vỡ khi thứ tự property đổi. Với lỗi 500, đừng chỉ assert status — đọc body, và bật log của host để thấy exception gốc.

Muốn khẳng định side effect đã ghi vào database, resolve scope từ chính factory. Đừng dựng một ServiceProvider riêng: nó không phải container mà request vừa dùng.

using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var saved = await db.Orders.SingleAsync(o => o.Id == created!.Id);
var itemCount = await db.OrderItems.CountAsync(i => i.OrderId == saved.Id);
Assert.Equal(2, itemCount);

factory.Services khởi động host test và trả về đúng provider đã xử lý request. Đây là cách kiểm tra dữ liệu thật mà không phải mock repository — và cũng là lý do UseInMemoryDatabase không đủ: nó không chứng minh được constraint hay transaction mà production sẽ áp.

Authentication: scheme giả, không phải JWT thật

Đừng ký JWT thật trong mỗi test. Một authentication handler đọc header test là đủ, và nó kiểm tra đúng phần bạn quan tâm: authorization policy, role, claim. Handler chỉ chạy khi có header, nhờ vậy test “chưa đăng nhập” vẫn nhận 401 như thật.

// File: Tests/Infrastructure/TestAuthHandler.cs
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;

public sealed class TestAuthHandler(
    IOptionsMonitor<AuthenticationSchemeOptions> options,
    ILoggerFactory logger,
    UrlEncoder encoder)
    : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.TryGetValue("X-Test-User", out var userId))
            return Task.FromResult(AuthenticateResult.NoResult());

        var claims = new[]
        {
            new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
            new Claim(ClaimTypes.Name, "test-user"),
            new Claim(ClaimTypes.Role, Request.Headers["X-Test-Role"].ToString())
        };

        var identity = new ClaimsIdentity(claims, "Test");
        var principal = new ClaimsPrincipal(identity);
        return Task.FromResult(AuthenticateResult.Success(
            new AuthenticationTicket(principal, "Test")));
    }
}

Đăng ký scheme trong ConfigureTestServices. Gán cả ba default scheme, vì nếu ứng dụng đã set DefaultAuthenticateScheme cho JwtBearer thì chỉ gọi AddAuthentication("Test") sẽ không ghi đè:

services.AddAuthentication(o =>
{
    o.DefaultScheme = "Test";
    o.DefaultAuthenticateScheme = "Test";
    o.DefaultChallengeScheme = "Test";
}).AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { });

Trong test, thêm helper tạo client có header. Cách này giữ được khác biệt giữa 401 và 403 — một khác biệt mà rất nhiều bộ test tích hợp làm mất khi mock IAuthorizationService.

public HttpClient ClientFor(Guid userId, string role = "Customer")
{
    var client = CreateClient();
    client.DefaultRequestHeaders.Add("X-Test-User", userId.ToString());
    client.DefaultRequestHeaders.Add("X-Test-Role", role);
    return client;
}

Database thật: Testcontainers 4.16 + Respawn 7

Container cho bạn đúng provider, đúng collation, đúng constraint. Một container cho cả collection test, Respawn dọn dữ liệu giữa các test. Dùng MigrateAsync, không dùng EnsureCreated, để schema test trùng schema production.

// File: Tests/Infrastructure/PostgresFixture.cs
using Microsoft.EntityFrameworkCore;
using Npgsql;
using Respawn;
using Testcontainers.PostgreSql;

public sealed class PostgresFixture : IAsyncLifetime
{
    private readonly PostgreSqlContainer _container = new PostgreSqlBuilder()
        .WithImage("postgres:17-alpine")
        .WithDatabase("appdb")
        .WithUsername("app")
        .WithPassword("secret")
        .Build();

    private Respawner _respawner = null!;
    public string ConnectionString => _container.GetConnectionString();

    public async ValueTask InitializeAsync()
    {
        await _container.StartAsync();

        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseNpgsql(ConnectionString).Options;
        await using var db = new AppDbContext(options);
        await db.Database.MigrateAsync();

        _respawner = await Respawner.CreateAsync(ConnectionString, new RespawnerOptions
        {
            DbAdapter = DbAdapter.Postgres,
            SchemasToInclude = new[] { "public" },
            TablesToIgnore = new[] { new Table("__EFMigrationsHistory") }
        });
    }

    public Task ResetAsync() => _respawner.ResetAsync(ConnectionString);

    public async ValueTask DisposeAsync() => await _container.DisposeAsync();
}

EnsureCreated và migration không tương đương. EnsureCreated dựng schema từ model hiện tại, bỏ qua migration, không có bảng history và không thể nâng cấp. Nếu production dùng migration để tạo computed column, seed dữ liệu hệ thống hay đổi kiểu cột, test với EnsureCreated đang chạy trên một schema chưa từng tồn tại. Nó chỉ phù hợp cho smoke test SQLite in-memory, nơi bạn chấp nhận đánh đổi.

Song song và cô lập

xUnit chạy song song giữa các collection, tuần tự trong cùng collection. Vì Respawn xóa toàn bộ bảng, mọi test chạm database phải nằm chung một collection:

[CollectionDefinition("postgres")]
public sealed class PostgresCollection : ICollectionFixture<PostgresFixture> { }

Đó là đánh đổi có chủ ý: một container, test DB chạy tuần tự, thời gian test tăng tuyến tính. Nếu bộ test lớn, chia theo module và cho mỗi module một container riêng — nhưng khi đó dữ liệu phải không phụ thuộc giữa các module. Đừng dùng chung một database in-memory theo tên: mọi test sẽ thấy dữ liệu của nhau và thứ tự chạy trở thành một phần của kết quả.

Khi nào integration test, khi nào unit test

Tiêu chí Unit test Integration test
Độ tin cậy của câu trả lời Kiểm tra công thức, nhánh logic Kiểm tra hợp đồng HTTP, EF mapping, auth
Tốc độ Mili giây Giây, cộng thời gian container
Khi fail, chỉ ra đâu Rất chính xác Chính xác vừa phải, cần đọc log
Nên chiếm tỉ lệ Phần lớn Mọi endpoint có rủi ro thật

Quy tắc thực dụng: mỗi endpoint có ít nhất một test happy path và một test lỗi qua WebApplicationFactory; logic rẽ nhánh phức tạp kiểm tra bằng unit test; E2E chỉ cho luồng người dùng quan trọng. Đừng viết test tích hợp cho mọi getter.

Pitfall thường gặp

  • services.BuildServiceProvider() bên trong ConfigureServices — đây là container thứ hai, không phải container phục vụ request. Bài viết cũ hay dùng nó để seed DB, và seed xong thì request vẫn thấy DB rỗng. Dùng factory.Services.CreateScope() trong test, hoặc seed bằng một IStartupFilter.
  • Chỉ xóa DbContextOptions<T> — từ EF Core 9, AddDbContext còn đăng ký IDbContextOptionsConfiguration<T>; xóa thiếu sẽ khiến cấu hình cũ (connection string production) tiếp tục được áp.
  • Không dispose factory — host và container rò rỉ qua các lần chạy, CI chậm dần. Implement IAsyncLifetime và dispose trong DisposeAsync.
  • Test phụ thuộc thứ tự — thường lộ ra khi chạy riêng từng test thì pass, chạy cả suite thì fail. Respawn là cách phát hiện sớm: nếu bỏ reset mà test vẫn pass, test đó đang dựa vào state có sẵn.

Nhìn sang 2027

.NET 11 đang ở RC3 và dự kiến GA trong tháng 11/2026, nên production vẫn là .NET 10 LTS. Với test, thay đổi đáng chú ý là MTP trở thành đường mặc định của dotnet test, kéo theo cú pháp filter và báo cáo khác VSTest. .NET Aspire đang dần thành cách chuẩn để dựng dependency (Postgres, Redis) cho môi trường tích hợp cục bộ, nhưng Testcontainers vẫn là lựa chọn ổn định trong CI không có Aspire.

Checklist

  • Test project target net10.0, tham chiếu project web, có Mvc.Testing 10.0.14.
  • Override ConfigureWebHost + ConfigureTestServices, không dùng BuildServiceProvider.
  • Thay DbContext bằng container thật, chạy MigrateAsync, reset bằng Respawn.
  • Gom test chạm DB vào một collection; tạo client mới cho mỗi test.
  • Assert ProblemDetails cho lỗi 4xx, không assert chuỗi JSON.
  • Dispose factory và container; kiểm tra suite chạy được khi đảo thứ tự test.

Bài liền trước trong series bàn về chọn framework unit test cho .NET. Nếu bạn đang thay dependency bằng mock, đọc Mocking với Moq và NSubstitute để biết khi nào mock là sai. Tiếp theo là kiểm thử E2E với Playwright, và tạo dữ liệu giả với AutoFixture và Bogus cho phần dữ liệu test.