| EF Core vs Dapper :👈 | 👉:Secure-API-Design |
ASP.NET Core Integration Testing Using WebApplicationFactory and Testcontainers |
ASP.NET Core Integration Testing Using WebApplicationFactory and Testcontainers
1. What Is Integration Testing?
Integration testing verifies whether different components of an application work correctly together.
For example, when testing an ASP.NET Core API, we may want to verify:
- HTTP request reaches the correct API endpoint.
- Routing and middleware work correctly.
- Dependency injection resolves services correctly.
- Business logic executes correctly.
- Entity Framework Core communicates with the database.
- Data is actually inserted and retrieved.
Unlike unit testing, integration testing checks the interaction between multiple application components.
2. What Is WebApplicationFactory?
WebApplicationFactory is provided by ASP.NET Core's Microsoft.AspNetCore.Mvc.Testing package.
It allows you to:
- Start your ASP.NET Core application inside a test process.
- Test API endpoints without deploying the application.
- Use an in-memory HTTP test server.
- Replace application services and configuration for testing.
- Send HTTP requests using HttpClient.
It uses TestServer by default, so you do not need to start a real web server or open a network port.
3. What Is Testcontainers?
Testcontainers is a library that allows automated tests to create and manage temporary Docker containers.
For example, it can start:
- SQL Server
- PostgreSQL
- MySQL
- Redis
- RabbitMQ
Instead of using a fake database, your integration tests can use a real database engine running in a Docker container.
4. Why Use Both Together?
- WebApplicationFactory: Starts the ASP.NET Core application for testing.
- Testcontainers: Starts real infrastructure such as SQL Server.
Architecture Diagram
5. Install Required NuGet Packages
For an ASP.NET Core application using xUnit, EF Core, and SQL Server:
dotnet add package Microsoft.AspNetCore.Mvc.Testing
dotnet add package Microsoft.NET.Test.Sdk
dotnet add package xunit
dotnet add package xunit.runner.visualstudio
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Testcontainers.MsSql
Use compatible package versions for your target .NET version. The examples below use the SQL Server Testcontainers module.
6. Example Application
Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
AppDbContext.cs
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(
DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Product> Products => Set<Product>();
}
ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetProducts()
{
var products = await _context.Products.ToListAsync();
return Ok(products);
}
[HttpPost]
public async Task<IActionResult> CreateProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(
nameof(GetProducts),
new { id = product.Id },
product);
}
}
Program.cs
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
app.MapControllers();
app.Run();
// Required for WebApplicationFactory<Program>
public partial class Program { }
7. Create an Integration Test Using Testcontainers
The test will start a real SQL Server container, configure the application to connect to it, and send HTTP requests to the API.
CustomWebApplicationFactory.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Testcontainers.MsSql;
public class CustomWebApplicationFactory
: WebApplicationFactory<Program>
{
private readonly string _connectionString;
public CustomWebApplicationFactory(string connectionString)
{
_connectionString = connectionString;
}
protected override void ConfigureWebHost(
IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
services.RemoveAll<DbContextOptions<AppDbContext>>();
services.RemoveAll<AppDbContext>();
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(_connectionString));
});
}
}
Important: The test factory removes the application's existing DbContext registration and replaces it with a connection to the temporary SQL Server container.
ProductIntegrationTests.cs
using System.Net;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Testcontainers.MsSql;
using Xunit;
public class ProductIntegrationTests : IAsyncLifetime
{
private readonly MsSqlContainer _dbContainer;
private CustomWebApplicationFactory _factory = null!;
private HttpClient _client = null!;
public ProductIntegrationTests()
{
_dbContainer = new MsSqlBuilder().Build();
}
public async Task InitializeAsync()
{
// Start SQL Server container
await _dbContainer.StartAsync();
// Start application using container connection string
_factory = new CustomWebApplicationFactory(
_dbContainer.GetConnectionString());
_client = _factory.CreateClient();
// Create database schema
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider
.GetRequiredService<AppDbContext>();
await db.Database.EnsureCreatedAsync();
}
[Fact]
public async Task CreateProduct_ShouldReturnCreated()
{
var product = new Product
{
Name = "Laptop",
Price = 50000
};
var response = await _client.PostAsJsonAsync(
"/api/products",
product);
Assert.Equal(
HttpStatusCode.Created,
response.StatusCode);
}
[Fact]
public async Task GetProducts_ShouldReturnProducts()
{
var product = new Product
{
Name = "Keyboard",
Price = 1500
};
var postResponse = await _client.PostAsJsonAsync(
"/api/products",
product);
postResponse.EnsureSuccessStatusCode();
var products = await _client.GetFromJsonAsync<List<Product>>(
"/api/products");
Assert.NotNull(products);
Assert.Contains(products, p => p.Name == "Keyboard");
}
public async Task DisposeAsync()
{
_client?.Dispose();
_factory?.Dispose();
await _dbContainer.DisposeAsync();
}
}
Note: This example uses EnsureCreatedAsync() for a simple demonstration. In production integration tests, consider applying the application's actual EF Core migrations using MigrateAsync() so that database schema changes are tested too.
8. How Does the Test Execute?
- xUnit starts the test.
- Testcontainers starts a SQL Server Docker container.
- The container provides a connection string.
- WebApplicationFactory starts the ASP.NET Core application.
- The test factory replaces the database connection.
- EF Core creates or migrates the database schema.
- HttpClient sends requests to the API.
- The API executes its normal application logic.
- EF Core reads or writes data in SQL Server.
- The test verifies the HTTP response and database behavior.
- The container is disposed when the test finishes.
9. Testcontainers vs In-Memory Database
| Area | EF Core InMemory | SQLite In-Memory | Testcontainers |
|---|---|---|---|
| Real database engine | No | SQLite engine | Yes |
| SQL Server compatibility | No | No | Yes, with SQL Server container |
| Database constraints | Not fully representative | SQLite constraints | Actual database constraints |
| Stored procedures | No | Not SQL Server procedures | Supported by SQL Server |
| Startup speed | Very fast | Fast | Slower due to containers |
| Best use | Simple tests | Lightweight relational tests | Real database integration tests |
10. Best Practices
- Use a real database container when database compatibility matters.
- Use a separate test database for every test run.
- Apply real EF Core migrations to verify schema changes.
- Clean up test data between tests or use isolated databases.
- Dispose of HttpClient, WebApplicationFactory, and containers correctly.
- Use parameterized configuration rather than hardcoded credentials.
- Do not run destructive tests against production databases.
- Keep unit tests separate from slower integration tests.
- Use Docker-enabled CI/CD agents to execute Testcontainers tests.
- Use realistic test data without depending on production data.
11. Common Mistakes
- Docker is not running: Testcontainers cannot start the required container.
- Wrong connection string: The application may connect to the development database instead of the container.
- Not replacing DbContext: The test may accidentally use the original database registration.
- Missing migrations: The container database may not have the required tables.
- Shared test data: Parallel tests may interfere with one another.
- Incorrect disposal: Containers may remain running after tests finish.
- Using EnsureCreatedAsync everywhere: This does not verify that production migrations execute correctly.
12. When Should You Use This Approach?
- Testing ASP.NET Core Web APIs.
- Testing EF Core database operations.
- Testing repository and service interactions.
- Testing database migrations.
- Testing microservices with dependencies such as SQL Server, Redis, and RabbitMQ.
- Running reliable integration tests in CI/CD pipelines.
13. Interview Questions
Q1. What is WebApplicationFactory?
It is a testing utility that creates an ASP.NET Core application test host and provides an HttpClient for integration testing.
Q2. What is Testcontainers?
It is a library that manages temporary Docker containers for dependencies such as databases, message brokers, and caches during tests.
Q3. Why use Testcontainers instead of EF Core InMemory?
EF Core InMemory does not behave like a relational database. Testcontainers lets tests use the actual database engine and verify database-specific behavior.
Q4. Can WebApplicationFactory test middleware?
Yes. Requests pass through the application's configured middleware pipeline in the test host.
Q5. Does WebApplicationFactory require IIS or Kestrel?
No. By default, it uses the in-memory TestServer and does not require a separately deployed application.
Q6. Can Testcontainers work with CI/CD?
Yes. The CI/CD agent must support Docker or provide a compatible container runtime.
Q7. What is the difference between EnsureCreatedAsync and MigrateAsync?
EnsureCreatedAsync creates a database schema directly without applying EF Core migrations. MigrateAsync applies pending migrations and is better suited to verifying the application's migration process.
Q8. Can multiple integration tests run in parallel?
Yes, but tests must use isolated databases or independent test data and avoid sharing mutable resources.
14. Final Summary
| Technology | Responsibility |
|---|---|
| xUnit | Runs tests and verifies assertions. |
| WebApplicationFactory | Starts the ASP.NET Core application for testing. |
| HttpClient | Sends HTTP requests to the test application. |
| Testcontainers | Starts real infrastructure in Docker containers. |
| EF Core | Communicates with the test database. |
Key takeaway: WebApplicationFactory tests your ASP.NET Core application through HTTP, while Testcontainers provides real external dependencies. Together, they help verify that your application works correctly as an integrated system.
| EF Core vs Dapper :👈 | 👉:Secure-API-Design |