Avalonia Field Guide
About

Module 4 · Lesson 15 of 16

Proof, not vibes

A headless harness boots the real app, renders every page, and asserts the things a screenshot cannot show.

35 minHeadless-tested

Every screenshot in this course was produced by the app that the lesson teaches. A tool called CourseApp.Verify starts Avalonia without a display, builds each page, renders it at 1280×800, and writes a PNG. Before it does, it runs an assertion for that page.

src/CourseApp.Verify/Program.cs
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Media.Imaging;
using Avalonia.Styling;
using Avalonia.Threading;
using CourseApp;
using CourseApp.Shell;

// Resolve relative to the repository root so `dotnet run` (whose working directory
// is the project folder) writes to the same place every time.
var repoRoot = AppContext.BaseDirectory;
while (repoRoot is not null && !Directory.Exists(Path.Combine(repoRoot, "src")))
    repoRoot = Directory.GetParent(repoRoot)?.FullName;
repoRoot ??= Directory.GetCurrentDirectory();

var shotsDir = args.Length > 0 && Path.IsPathRooted(args[0])
    ? args[0]
    : Path.Combine(repoRoot, args.Length > 0 ? args[0] : "web/public/shots");
Directory.CreateDirectory(shotsDir);

AppBuilder.Configure<App>()
    .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
    .UseSkia()
    .WithInterFont()
    .SetupWithoutStarting();

var failures = new List<string>();

foreach (var lesson in LessonCatalog.All)
{
    RunAssertions(lesson, failures);

    foreach (var (variant, suffix) in new[] { (ThemeVariant.Light, "light"), (ThemeVariant.Dark, "dark") })
    {
        Application.Current!.RequestedThemeVariant = variant;

        var view = lesson.Create();
        var window = new Window
        {
            Width = 1280,
            Height = 800,
            WindowDecorations = WindowDecorations.None,
            CanResize = false,
            Content = view,
        };

        window.Show();
        Dispatcher.UIThread.RunJobs();

        var frame = window.CaptureRenderedFrame();
        if (frame is null)
        {
            failures.Add($"{lesson.Slug}/{suffix}: headless capture returned null");
        }
        else
        {
            var path = Path.Combine(shotsDir, $"{lesson.Slug}-{suffix}.png");
            frame.Save(path, new PngBitmapEncoderOptions());
            Console.WriteLine($"  rendered {Path.GetFileName(path)}  {frame.PixelSize.Width}×{frame.PixelSize.Height}");
        }

        window.Close();
    }
}

Console.WriteLine();
if (failures.Count > 0)
{
    Console.Error.WriteLine($"{failures.Count} failure(s):");
    foreach (var failure in failures)
        Console.Error.WriteLine($"  - {failure}");
    return 1;
}

Console.WriteLine($"all {LessonCatalog.All.Count} lessons verified");
return 0;

static void RunAssertions(LessonNavItem lesson, List<string> failures)
{
    try
    {
        lesson.Verify?.Invoke();
        Console.WriteLine($"verified {lesson.Slug}");
    }
    catch (Exception ex)
    {
        failures.Add($"{lesson.Slug}: {ex.Message}");
    }
}
Screenshot of the testing lesson sample
The lesson's sample, rendered headlessly at 1280×800. Light and dark are both captured.

Headless is a platform, not a mock

AppBuilder.Configure<App>()
    .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
    .UseSkia()
    .WithInterFont()
    .SetupWithoutStarting();

UseHeadless supplies a windowing platform with no display server. UseSkia gives it a real rasterizer, so text shaping, layout, and Render behave exactly as they do on X11 or Windows. CaptureRenderedFrame() grabs the composited frame.

That combination is what makes the screenshots trustworthy: they are the actual pixels, produced by the actual controls.

Assertions live next to the samples

Each catalog entry carries a verification delegate:

new("forms", "07", "Validation that blocks the button", () => new SignupView(), () =>
{
    var vm = new SignupViewModel { Email = "not-an-email", Password = "short" };
    if (vm.SubmitCommand.CanExecute(null))
        throw new InvalidOperationException("submit should be blocked");
});

This is deliberate. The sample and its proof are one object. A refactor that breaks the rule cannot quietly update the screenshot; the verifier exits non-zero, the content build refuses to run, and nothing deploys.

What screenshots cannot prove

  • That a binding updates rather than showing a lucky initial value.
  • That a command is disabled at the right time.
  • That navigation actually swapped the page.
  • That a control received data instead of drawing an empty frame.

Those are the assertions. The image proves layout and colour; the assertion proves behaviour. You need both, which is why this lesson renders a page and checks its numbers.

Golden images are not a substitute for assertions. A PNG diff tells you something changed. It does not tell you whether the change was correct, and it fails on every font-rendering difference between machines.

If you prefer xUnit

Avalonia.Headless.XUnit gives you [AvaloniaFact] with the same platform. Use it for a real test suite; keep the render harness for artifacts. Both call the same view models, because the view models do not know either exists.

Try it

  1. Break the cart total on purpose (remove the PropertyChanged call), run dotnet run --project src/CourseApp.Verify, and read the failure. Restore it.
  2. Add an assertion for lesson 3 that fails if the star ratio is wrong, then change 2* to 3* and watch it fail.
  3. Delete one PNG and run the content build. The error names the missing file.

Next: from dotnet run to a desktop.

Files this lesson draws from

  • src/CourseApp.Verify/Program.cs
  • src/CourseApp/Shell/LessonCatalog.cs

VerifiedThe verifier runs the sample checks on this page and refuses to capture the screenshot unless every one passes.

Back to top