Lesson 3 of 8
Integration Tests - WebApplicationFactory<T>
WebApplicationFactory<T> spins up the real ASP.NET Core server in-memory with all middleware, DI, routing, auth, and filters - without opening a network port. HttpClient sends real HTTP requests and gets real responses, making integration tests extremely high-confidence.
WebApplicationFactory Custom Setup
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
// ━━ Custom factory - swap real DB with in-memory for tests ━━
public class ApiWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
// Remove real EF Core DbContext registration
var descriptor = services
.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
if (descriptor is not null) services.Remove(descriptor);
// Use in-memory database per test run
services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase($"TestDb_{Guid.NewGuid()}"));
// Replace external services with mocks
var emailService = services
.SingleOrDefault(d => d.ServiceType == typeof(IEmailService));
if (emailService is not null) services.Remove(emailService);
services.AddSingleton<IEmailService, NoOpEmailService>();
});
builder.UseEnvironment("Testing");
}
}
// ━━ Base test class with factory ━━
public abstract class IntegrationTestBase(ApiWebApplicationFactory factory)
: IClassFixture<ApiWebApplicationFactory>
{
protected HttpClient Client { get; } = factory.CreateClient(
new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
BaseAddress = new Uri("https://localhost")
});
// Helper: authenticate as a specific user
protected async Task<HttpClient> CreateAuthenticatedClientAsync(string userId, string[] roles)
{
// Call login endpoint or generate test JWT
var response = await Client.PostAsJsonAsync("/api/auth/login",
new { Email = "test@example.com", Password = "TestPassword123!" });
var token = await response.Content.ReadFromJsonAsync<LoginResponse>();
var authClient = factory.CreateClient();
authClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token!.AccessToken);
return authClient;
}
// Helper: seed test data
protected async Task SeedAsync(Action<AppDbContext> seed)
{
using var scope = factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
seed(db);
await db.SaveChangesAsync();
}
}
// ━━ Product API integration tests ━━
public class ProductsApiTests(ApiWebApplicationFactory factory)
: IntegrationTestBase(factory)
{
[Fact]
public async Task GET_Products_ReturnsOkWithList()
{
// Arrange
await SeedAsync(db => db.Products.AddRange(
new Product { Id = Guid.NewGuid(), Name = "Widget" },
new Product { Id = Guid.NewGuid(), Name = "Gadget" }));
// Act
var response = await Client.GetAsync("/api/v1/products");
// Assert
response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<PagedResult<ProductDto>>();
body!.Items.Should().HaveCount(2);
}
[Fact]
public async Task POST_CreateProduct_WithoutAuth_Returns401()
{
var response = await Client.PostAsJsonAsync("/api/v1/products",
new { Name = "Widget", Price = 9.99 });
response.StatusCode.Should().Be(System.Net.HttpStatusCode.Unauthorized);
}
[Fact]
public async Task POST_CreateProduct_InvalidData_Returns400()
{
var authClient = await CreateAuthenticatedClientAsync("admin-id", ["Admin"]);
var response = await authClient.PostAsJsonAsync("/api/v1/products",
new { Name = "", Price = -1 }); // invalid
response.StatusCode.Should().Be(System.Net.HttpStatusCode.BadRequest);
var problem = await response.Content.ReadFromJsonAsync<ValidationProblemDetails>();
problem!.Errors.Should().ContainKey("Name");
}
}
// Stub types
class AppDbContext { public System.Collections.Generic.List<Product> Products { get; set; } = []; public Task<int> SaveChangesAsync() => Task.FromResult(0); }
class Product { public Guid Id { get; set; } public string Name { get; set; } = ""; }
record ProductDto(Guid Id, string Name);
record PagedResult<T>(System.Collections.Generic.List<T> Items);
record LoginResponse(string AccessToken);
class ValidationProblemDetails { public System.Collections.Generic.Dictionary<string, string[]> Errors { get; set; } = []; }
interface IEmailService { }
class NoOpEmailService : IEmailService { }Tip
Tip
Practice Integration Tests WebApplicationFactoryT in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Integration Tests WebApplicationFactoryT from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Integration Tests WebApplicationFactoryT is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?