Testing
The best tests of a Magicalizer API go through HTTP: they check what the clients get, including the parts you didn’t
write (the routes, the binding, the validation, the errors). ASP.NET Core runs the application in memory for that,
with WebApplicationFactory, and each test class gets its own database. The tests of docs/samples/Recipes are in
docs/samples/Recipes.Tests, and Magicalizer itself is tested the same way.
The project
A test project (xUnit v3 here) that references the web application:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<OutputType>Exe</OutputType>
<RootNamespace>App.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" />
<PackageReference Include="xunit.v3" Version="3.2.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Recipes\Recipes.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>
The Program class of a web application with the top-level statements is public in .NET 10, so the tests reach it
without public partial class Program.
The factory
The factory starts the application with its own SQLite file, so the test classes don’t share the data and can run in parallel, and deletes the file afterwards:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
namespace App.Tests;
// Starts the application in memory with its own SQLite database, which is deleted afterwards.
public class AppFactory : WebApplicationFactory<Program>
{
private readonly string databasePath = Path.Combine(Path.GetTempPath(), $"recipes-{Guid.NewGuid():N}.db");
// Creates a client of the user (the sample authenticates by the X-User header).
public HttpClient CreateClient(string user)
{
HttpClient client = this.CreateClient();
client.DefaultRequestHeaders.Add("X-User", user);
return client;
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseSetting("ConnectionStrings:Default", $"Data Source={this.databasePath};Pooling=false");
}
public override async ValueTask DisposeAsync()
{
await base.DisposeAsync();
File.Delete(this.databasePath);
}
}
UseSettingoverrides the connection string ofappsettings.jsonbefore the application reads it.Pooling=falsecloses the connections, so the file can be deleted.- The sample creates the database with
EnsureCreatedat the start. An application with migrations callsDatabase.Migrate()instead, or the factory does it. CreateClient(user)signs the client in by the header of the sample authentication. With a real scheme, replace it in the factory by a test one (ConfigureTestServicesandAddAuthentication).
The tests
Each test class gets one factory (IClassFixture), and its tests share the application and the database. The tests
create the data they need, so they don’t depend on each other:
using System.Net;
using System.Net.Http.Json;
using App.Api.Dto;
namespace App.Tests;
public class NotebookTests : IClassFixture<AppFactory>
{
private readonly AppFactory factory;
public NotebookTests(AppFactory factory)
{
this.factory = factory;
}
[Fact]
public async Task Anonymous_user_gets_401()
{
HttpClient client = this.factory.CreateClient();
HttpResponseMessage response = await client.GetAsync("/v1/notebooks", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task User_sees_only_own_notebooks()
{
CancellationToken cancellationToken = TestContext.Current.CancellationToken;
HttpClient alice = this.factory.CreateClient("alice");
HttpClient bob = this.factory.CreateClient("bob");
HttpResponseMessage created = await alice.PostAsJsonAsync("/v1/notebooks", new Notebook { Name = "Alice's" }, cancellationToken);
Notebook? notebook = await created.Content.ReadFromJsonAsync<Notebook>(cancellationToken);
Assert.Equal(HttpStatusCode.Created, created.StatusCode);
Notebook[]? bobsNotebooks = await bob.GetFromJsonAsync<Notebook[]>("/v1/notebooks", cancellationToken);
HttpResponseMessage bobsResponse = await bob.GetAsync($"/v1/notebooks/{notebook!.Id}", cancellationToken);
Assert.DoesNotContain(bobsNotebooks!, n => n.Id == notebook.Id);
Assert.Equal(HttpStatusCode.NotFound, bobsResponse.StatusCode);
}
[Fact]
public async Task Deleted_note_is_hidden()
{
CancellationToken cancellationToken = TestContext.Current.CancellationToken;
HttpClient alice = this.factory.CreateClient("alice");
HttpResponseMessage createdNotebook = await alice.PostAsJsonAsync("/v1/notebooks", new Notebook { Name = "Drafts" }, cancellationToken);
Notebook? notebook = await createdNotebook.Content.ReadFromJsonAsync<Notebook>(cancellationToken);
HttpResponseMessage createdNote = await alice.PostAsJsonAsync("/v1/notes", new Note { Notebook = notebook, Title = "Draft" }, cancellationToken);
Note? note = await createdNote.Content.ReadFromJsonAsync<Note>(cancellationToken);
HttpResponseMessage deleted = await alice.DeleteAsync($"/v1/notes/{note!.Id}", cancellationToken);
Notebook? notebookWithNotes = await alice.GetFromJsonAsync<Notebook>($"/v1/notebooks/{notebook!.Id}?include=notes", cancellationToken);
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
Assert.Empty(notebookWithNotes!.Notes!);
}
}
The DTOs of the application are the request and response types of the tests, so the tests break at the compile time when the contract changes.
Running
dotnet test
Passed! - Failed: 0, Passed: 3, Skipped: 0, Total: 3, Duration: 1 s - Recipes.Tests.dll (net10.0)
Other databases
SQLite is fast and needs no server, but it isn’t your production database: the comparison of the strings, the dates, and the errors of the constraints differ. If production is PostgreSQL or SQL Server, run the tests on it too (e.g. in CI, with the server in a container): the factory sets a connection string of a new database for each test class and deletes the database afterwards.
What else to test
- The startup: a test that the application starts and serves the expected DTOs catches a DTO that is skipped (e.g. without a model). The startup diagnostics log the reason.
- The custom services: through the API as above, or directly from a scope of the factory
(
factory.Services.CreateScope()), with the current user and the other services replaced byConfigureTestServices. - The validators: as plain classes, with
TestValidateof FluentValidation.