Unit tests with mocked repositories and isolated controller calls are fast, but they cannot catch real integration failures in an ASP.NET Core MVC application. Misconfigured routing attributes, middleware ordering bugs, antiforgery token mismatches, custom model binder errors, or LINQ-to-SQL translation issues that compile fine against an in-memory provider often surface only when the full HTTP pipeline runs against a real relational database.
WebApplicationFactory<TProgram> boots your actual ASP.NET Core MVC application in memory and exposes an HttpClient that exercises routing, filters, model binding, authentication/authorization, and Razor/API responses end-to-end. Pairing it with Testcontainers spins up disposable, real database containers (such as SQL Server or PostgreSQL) per test run or test collection, giving you realistic persistence behavior without polluting shared developer or staging databases. This guide walks through structuring a fixture, overriding configuration and services cleanly, isolating test state, and writing end-to-end MVC integration tests.
1. Architectural Blueprint & Test Isolation Strategy
A reliable integration test suite balances realistic infrastructure with fast, deterministic isolation:
Layer / Concern |
Approach in Integration Tests |
Why It Matters |
HTTP Pipeline & MVC Routing |
WebApplicationFactory<Program> + HttpClient
|
Tests real routing, model binders, filters, validation, and controller/view responses rather than invoking action methods directly. |
Database Engine |
Testcontainers.MsSql (or Testcontainers.PostgreSql)
|
Exercises real SQL dialects, constraints, migrations, and EF Core query translations instead of UseInMemoryDatabase. |
Test Data Isolation |
Per-test unique records / Respawn reset / fresh database per fixture |
Prevents cross-test pollution when tests run in parallel or in arbitrary order. |
External Dependencies |
Replace outbound HttpMessageHandler or external clients in ConfigureTestServices |
Keeps tests deterministic and independent of third-party network availability. |
[xUnit Test Class] ──uses──> [MvcIntegrationTestFixture (IClassFixture)]
│
┌──────────────────────────┴──────────────────────────┐
▼ ▼
[MsSqlContainer (Testcontainers)] [WebApplicationFactory<Program>]
• Starts real SQL Server container • Overrides ConnectionStrings:DefaultConnection
• Applies EF Core migrations once • Runs real ASP.NET Core MVC middleware & filters
• Provides HttpClient for HTTP requests
2. Sample MVC Application Target (OrdersController & AppDbContext)
To keep the tests concrete, suppose our ASP.NET Core MVC application exposes an orders endpoint and Razor/JSON response backed by Entity Framework Core and SQL Server:
C#
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
public sealed class Order
{
public Guid Id { get; set; }
public string OrderNumber { get; set; } = string.Empty;
public string CustomerEmail { get; set; } = string.Empty;
public decimal TotalAmount { get; set; }
public string Status { get; set; } = "Pending";
public DateTimeOffset CreatedAtUtc { get; set; }
}
public sealed class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(entity =>
{
entity.HasKey(o => o.Id);
entity.Property(o => o.OrderNumber).HasMaxLength(32).IsRequired();
entity.HasIndex(o => o.OrderNumber).IsUnique();
entity.Property(o => o.CustomerEmail).HasMaxLength(200).IsRequired();
entity.Property(o => o.TotalAmount).HasColumnType("decimal(18,2)");
entity.Property(o => o.Status).HasMaxLength(32).IsRequired();
});
}
}
public sealed record CreateOrderRequest(
string OrderNumber,
string CustomerEmail,
decimal TotalAmount
);
public sealed record OrderResponse(
Guid Id,
string OrderNumber,
string CustomerEmail,
decimal TotalAmount,
string Status
);
[ApiController]
[Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
private readonly AppDbContext _dbContext;
public OrdersController(AppDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpPost]
public async Task<IActionResult> Create(
[FromBody] CreateOrderRequest request,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(request.OrderNumber) ||
string.IsNullOrWhiteSpace(request.CustomerEmail) ||
request.TotalAmount <= 0m)
{
return BadRequest(new { Error = "Invalid order payload." });
}
string normalizedNumber = request.OrderNumber.Trim().ToUpperInvariant();
bool duplicateExists = await _dbContext.Orders
.AsNoTracking()
.AnyAsync(o => o.OrderNumber == normalizedNumber, cancellationToken);
if (duplicateExists)
{
return Conflict(new { Error = $"Order '{normalizedNumber}' already exists." });
}
var order = new Order
{
Id = Guid.NewGuid(),
OrderNumber = normalizedNumber,
CustomerEmail = request.CustomerEmail.Trim(),
TotalAmount = decimal.Round(request.TotalAmount, 2, MidpointRounding.AwayFromZero),
Status = "Confirmed",
CreatedAtUtc = DateTimeOffset.UtcNow
};
_dbContext.Orders.Add(order);
await _dbContext.SaveChangesAsync(cancellationToken);
var response = new OrderResponse(
order.Id,
order.OrderNumber,
order.CustomerEmail,
order.TotalAmount,
order.Status);
return CreatedAtAction(nameof(GetById), new { id = order.Id }, response);
}
[HttpGet("{id:guid}")]
public async Task<IActionResult> GetById(Guid id, CancellationToken cancellationToken)
{
var order = await _dbContext.Orders
.AsNoTracking()
.Where(o => o.Id == id)
.Select(o => new OrderResponse(
o.Id,
o.OrderNumber,
o.CustomerEmail,
o.TotalAmount,
o.Status))
.FirstOrDefaultAsync(cancellationToken);
return order is null ? NotFound() : Ok(order);
}
}
Ensure your entry point (Program.cs) exposes Program to the test project (either via top-level statements with <InternalsVisibleTo> or an explicit public partial class Program { }).
C#
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();
app.Run();
public partial class Program { }
3. Building the WebApplicationFactory + Testcontainers Fixture
Using IAsyncLifetime in xUnit lets Testcontainers start the SQL Server container asynchronously before tests run, apply Entity Framework Core migrations once, and dispose of the container cleanly afterward.
C#
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Testcontainers.MsSql;
using Xunit;
public sealed class MvcIntegrationTestFixture : WebApplicationFactory<Program>, IAsyncLifetime
{
private readonly MsSqlContainer _sqlContainer = new MsSqlBuilder()
.WithImage("mcr.microsoft.com/mssql/server:2022-latest")
.WithPassword("Strong!Passw0rd#2026")
.Build();
public string ConnectionString => _sqlContainer.GetConnectionString();
public async Task InitializeAsync()
{
await _sqlContainer.StartAsync();
// Force host creation and run EF Core migrations against the containerized SQL Server
using IServiceScope scope = Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await dbContext.Database.MigrateAsync();
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureAppConfiguration((_, configBuilder) =>
{
var overrides = new Dictionary<string, string?>
{
["ConnectionStrings:DefaultConnection"] = _sqlContainer.GetConnectionString()
};
configBuilder.AddInMemoryCollection(overrides);
});
builder.ConfigureServices(services =>
{
// Re-register AppDbContext with the container connection string in case configuration
// was captured before the container started
ServiceDescriptor? existingDescriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
if (existingDescriptor is not null)
{
services.Remove(existingDescriptor);
}
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(_sqlContainer.GetConnectionString()));
});
}
public new async Task DisposeAsync()
{
await base.DisposeAsync();
await _sqlContainer.DisposeAsync();
}
}
4. Writing End-to-End Integration Tests
With MvcIntegrationTestFixture, tests issue real HTTP requests through HttpClient, verify status codes, headers, and response payloads, and confirm rows are persisted in SQL Server. Using unique order numbers per test avoids collisions even when tests share the container instance.
C#
using System.Net;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public sealed class OrdersControllerIntegrationTests : IClassFixture<MvcIntegrationTestFixture>
{
private readonly MvcIntegrationTestFixture _fixture;
private readonly HttpClient _client;
public OrdersControllerIntegrationTests(MvcIntegrationTestFixture fixture)
{
_fixture = fixture;
_client = fixture.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
}
[Fact]
public async Task CreateAndGetOrder_ValidPayload_PersistsInSqlServerAndReturnsCreated()
{
string uniqueOrderNumber = $"ORD-{Guid.NewGuid():N}"[..16];
var createRequest = new CreateOrderRequest(
OrderNumber: uniqueOrderNumber,
CustomerEmail: "[email protected]",
TotalAmount: 499.50m);
HttpResponseMessage createResponse = await _client.PostAsJsonAsync("/api/orders", createRequest);
Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode);
Assert.NotNull(createResponse.Headers.Location);
OrderResponse? created = await createResponse.Content.ReadFromJsonAsync<OrderResponse>();
Assert.NotNull(created);
Assert.NotEqual(Guid.Empty, created.Id);
Assert.Equal(uniqueOrderNumber.ToUpperInvariant(), created.OrderNumber);
Assert.Equal("Confirmed", created.Status);
// Fetch via the returned Location URI to verify end-to-end round-trip
HttpResponseMessage getResponse = await _client.GetAsync(createResponse.Headers.Location);
Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
OrderResponse? fetched = await getResponse.Content.ReadFromJsonAsync<OrderResponse>();
Assert.NotNull(fetched);
Assert.Equal(created.Id, fetched.Id);
Assert.Equal(499.50m, fetched.TotalAmount);
// Confirm directly in SQL Server via a scoped DbContext
using IServiceScope scope = _fixture.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
bool existsInDb = await dbContext.Orders.AnyAsync(o => o.Id == created.Id);
Assert.True(existsInDb);
}
[Fact]
public async Task CreateOrder_DuplicateOrderNumber_ReturnsConflict409()
{
string uniqueOrderNumber = $"DUP-{Guid.NewGuid():N}"[..16];
var firstRequest = new CreateOrderRequest(uniqueOrderNumber, "[email protected]", 100.00m);
var secondRequest = new CreateOrderRequest(uniqueOrderNumber.ToLowerInvariant(), "[email protected]", 200.00m);
HttpResponseMessage firstResponse = await _client.PostAsJsonAsync("/api/orders", firstRequest);
Assert.Equal(HttpStatusCode.Created, firstResponse.StatusCode);
HttpResponseMessage duplicateResponse = await _client.PostAsJsonAsync("/api/orders", secondRequest);
Assert.Equal(HttpStatusCode.Conflict, duplicateResponse.StatusCode);
}
[Fact]
public async Task CreateOrder_NonPositiveAmount_ReturnsBadRequest400()
{
var invalidRequest = new CreateOrderRequest(
OrderNumber: $"INV-{Guid.NewGuid():N}"[..16],
CustomerEmail: "[email protected]",
TotalAmount: 0m);
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/orders", invalidRequest);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
}
5. Practical CI/CD & Performance Tips
When running WebApplicationFactory<TProgram> and Testcontainers in local development or CI pipelines:
Share the container across test classes via a Collection Fixture: Starting a database container takes a few seconds. Use [CollectionDefinition] and ICollectionFixture<MvcIntegrationTestFixture> if multiple test classes share the same database instance so SQL Server boots once per test run rather than once per class.
Avoid EnsureCreated() when testing migrations: Always call Database.MigrateAsync() so your tests validate real schema migrations rather than creating tables directly from the current model snapshot.
Keep test data scoped: Generate unique identifiers per test or clean up/reset tables between tests so assertions never depend on execution order.
6. Conclusion
Combining WebApplicationFactory<TProgram> with Testcontainers gives ASP.NET Core MVC teams high-confidence end-to-end verification without maintaining fragile shared test databases or relying on unrealistic in-memory fakes. Your tests exercise the actual HTTP pipeline, routing, model binding, validation, and SQL Server persistence while keeping container setup and teardown encapsulated inside a clean test fixture.
ASP.NET Core MVCintegration testingWebApplicationFactoryTestcontainersxUnitEntity Framework CoreSQL Server
Join the conversation! Your thoughts help the community grow.