Lesson 17 of 93 · 8 min read · Updated

Snapshot Testing in .NET: From a Hand-Made Approval Test to Verify with Scrubbing

Some outputs are too large for individual assertions: a rendered invoice, a serialized API response, a generated report. Writing thirty Assert.Equal lines for them is slow and fragile. A snapshot test saves the approved output to a file once and compares every later run against it. This lesson builds the mechanism by hand first, so you see exactly how it works, and then does the same with the Verify library, which automates the workflow and cleans up values that change on every run.

Technical Requirements

  1. .NET 11 SDK
  2. xunit 2.9.3 (with xunit.runner.visualstudio and Microsoft.NET.Test.Sdk)
  3. Verify.Xunit 31.12.5

The Idea and the Code Under Test

A snapshot test has three steps:

  1. Produce the output and serialize it to text.
  2. Compare it with an approved reference file, named *.verified.txt, that lives in source control.
  3. If they differ, fail. The new output only passes after a person reviews it and approves it on purpose.

The candidate here is an invoice renderer. It produces multi-line text with aligned columns (FATURA means "invoice" and TOPLAM means "total").

M02.XUnitBasics/InvoiceRenderer.cs

public static class InvoiceRenderer
{
public static string Render(string customer, DateOnly issuedOn, IReadOnlyList<(string Sku, int Qty, decimal UnitPrice)> lines)
{
var culture = CultureInfo.GetCultureInfo("tr-TR");
var builder = new StringBuilder();

builder.AppendLine("FATURA");
builder.AppendLine("======");
builder.AppendLine($"Müşteri : {customer}");
builder.AppendLine($"Tarih : {issuedOn.ToString("dd.MM.yyyy", culture)}");
builder.AppendLine();
builder.AppendLine("SKU ADET BİRİM TUTAR");

decimal total = 0;
foreach (var (sku, qty, unitPrice) in lines)
{
var lineTotal = qty * unitPrice;
total += lineTotal;
// WARNING: we pass the culture EXPLICITLY with string.Create(culture, ...).
// Otherwise the output depends on the culture of the machine running the test,
// and the snapshot test breaks on another machine (a brittle test!).
builder.AppendLine(string.Create(culture,
$"{sku,-12} {qty,5} {unitPrice,9:N2} {lineTotal,10:N2}"));
}

builder.AppendLine();
builder.AppendLine(string.Create(culture, $"TOPLAM {total,32:N2}"));
return builder.ToString();
}
}

Note the comment about culture. Number formatting such as N2 uses the current culture unless you pass one. On a machine with an English culture, 1.500,00 would become 1,500.00 and the snapshot would fail even though nothing is wrong. Anything that varies by machine, such as culture, time zone, line endings or machine name, must be fixed in the code or removed before comparison.

A Hand-Made Snapshot Test

M02.XUnitBasics.Tests/SnapshotTests.cs

public class SnapshotTests
{
[Fact]
public void Render_ProducesApprovedInvoiceLayout()
{
// Arrange — NO volatile values: the date is fixed (normalization).
var lines = new List<(string, int, decimal)>
{
("KLAVYE-01", 2, 750m),
("MOUSE-01", 1, 250m),
("MONITOR-27", 1, 5_000m),
};

// Act
var rendered = InvoiceRenderer.Render(
customer: "Ada Yazılım A.Ş.",
issuedOn: new DateOnly(2026, 3, 14),
lines: lines);

// Assert — compare with the approved reference.
AssertMatchesSnapshot("Invoice.verified.txt", rendered);
}

/// <summary>
/// A small "hand-made Verify". If the reference file is missing, it writes a .received
/// file and fails the test, so the developer can review and approve the output.
/// </summary>
private static void AssertMatchesSnapshot(string fileName, string actual)
{
var baseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
var snapshotPath = Path.Combine(baseDirectory, "Snapshots", fileName);

// Normalize line endings: the Windows (CRLF) vs Linux (LF) difference
// must not break the test. This is also a "volatile value" normalization.
static string Normalize(string text) => text.Replace("\r\n", "\n").TrimEnd();

if (!File.Exists(snapshotPath))
{
var receivedPath = snapshotPath.Replace(".verified.txt", ".received.txt");
Directory.CreateDirectory(Path.GetDirectoryName(receivedPath)!);
File.WriteAllText(receivedPath, actual);
Assert.Fail(
$"Onaylanmış snapshot bulunamadı. Çıktıyı inceleyin ve onaylayın: {receivedPath}");
}

var expected = File.ReadAllText(snapshotPath);
Assert.Equal(Normalize(expected), Normalize(actual));
}
}

The helper reads the approved file from the output folder. The test project copies it there with <None Update="Snapshots\*.verified.txt" CopyToOutputDirectory="PreserveNewest" />. When the file is missing, it writes the actual output next to it as Invoice.received.txt and fails with "approved snapshot not found, review the output and approve it". The approved file looks like this:

M02.XUnitBasics.Tests/Snapshots/Invoice.verified.txt

FATURA
======
Müşteri : Ada Yazılım A.Ş.
Tarih : 14.03.2026

SKU ADET BİRİM TUTAR
KLAVYE-01 2 750,00 1.500,00
MOUSE-01 1 250,00 250,00
MONITOR-27 1 5.000,00 5.000,00

TOPLAM 6.750,00

To see the cycle, delete the verified file, run the tests, inspect the received file, and copy it back as the approved version. Run these commands from the test project folder:

rm Snapshots/Invoice.verified.txt
dotnet test
cp bin/Debug/net11.0/Snapshots/Invoice.received.txt Snapshots/Invoice.verified.txt

The Same Test with Verify

Verify automates all of this. Add Verify.Xunit and the static using <Using Include="VerifyXunit.Verifier" Static="true" />, and the whole helper becomes one line:

M02.XUnitBasics.Tests/VerifySnapshotTests.cs

public class VerifySnapshotTests
{
/// <summary>We keep Verify files in a separate folder from the hand-made snapshots.</summary>
private const string SnapshotDirectory = "Snapshots/Verify";

[Fact]
public Task Render_InvoiceText_MatchesVerifiedSnapshot()
{
// Arrange — fixed date: text output is not scrubbed, so we normalize it ourselves.
var lines = new List<(string, int, decimal)>
{
("KLAVYE-01", 2, 750m),
("MOUSE-01", 1, 250m),
("MONITOR-27", 1, 5_000m),
};

// Act
var rendered = InvoiceRenderer.Render(
customer: "Ada Yazılım A.Ş.",
issuedOn: new DateOnly(2026, 3, 14),
lines: lines);

// Assert — one line: compare with the verified file.
return Verify(rendered).UseDirectory(SnapshotDirectory);
}

The test returns the Task from Verify. On the first run, Verify writes VerifySnapshotTests.Render_InvoiceText_MatchesVerifiedSnapshot.received.txt into the source folder (not bin) and fails. You review the content and accept it, either by renaming it to .verified.txt or with the "accept" button of a diff tool. On later runs, any difference fails the test and Verify can open a diff tool that shows exactly what changed. The file name comes from the class and method names, so you never name snapshot files by hand.

Object Graphs and Scrubbing

Verify is not limited to strings. Pass an object, and it serializes it to readable, JSON-like text. Values that change on every run are replaced with stable placeholders, which is called scrubbing.

M02.XUnitBasics.Tests/VerifySnapshotTests.cs

[Fact]
public Task ObjectGraph_IsSerialized_AndVolatileValuesAreScrubbed()
{
// Arrange — an object graph with values that CHANGE on every run.
var keyboard = new Product("KLAVYE-01", "Mekanik Klavye", 750m, stock: 10);
keyboard.Reserve(2);

var order = new
{
OrderId = Guid.NewGuid(), // different every time → Guid_1
CreatedAt = DateTime.UtcNow, // different every time → DateTime_1
Customer = "Ada Yazılım A.Ş.",
Lines = new[]
{
new { keyboard.Sku, keyboard.Name, Quantity = 2, keyboard.Price },
},
RemainingStock = keyboard.Stock,
};

// Act + Assert — Verify serializes the object and scrubs the volatile values.
return Verify(order).UseDirectory(SnapshotDirectory);
}

M02.XUnitBasics.Tests/Snapshots/Verify/VerifySnapshotTests.ObjectGraph_IsSerialized_AndVolatileValuesAreScrubbed.verified.txt

{
OrderId: Guid_1,
CreatedAt: DateTime_1,
Customer: Ada Yazılım A.Ş.,
Lines: [
{
Sku: KLAVYE-01,
Name: Mekanik Klavye,
Quantity: 2,
Price: 750.0
}
],
RemainingStock: 8
}

The Guid and DateTime became Guid_1 and DateTime_1. If the same value appeared twice, both places would show the same placeholder, so the snapshot still proves that two fields hold the same id. Automatic scrubbing only works for typed values, though. A GUID stored in a string, or the name of the build machine, needs explicit rules:

M02.XUnitBasics.Tests/VerifySnapshotTests.cs

[Fact]
public Task CustomScrubbing_RemovesMembersAndMachineSpecificValues()
{
// Arrange — fields that are NOT part of the business contract: trace id and machine name.
var response = new
{
Status = "Approved",
Amount = 1_250.50m,
TraceId = Guid.NewGuid().ToString("N"), // a Guid inside a string → not caught automatically
Machine = Environment.MachineName, // different on every developer's machine
};

// Act + Assert
return Verify(response)
.IgnoreMember("TraceId") // remove the member from the snapshot entirely
.ScrubMachineName() // replace the machine name with "TheMachineName"
.UseDirectory(SnapshotDirectory);
}
}

M02.XUnitBasics.Tests/Snapshots/Verify/VerifySnapshotTests.CustomScrubbing_RemovesMembersAndMachineSpecificValues.verified.txt

{
Status: Approved,
Amount: 1250.50,
Machine: TheMachineName
}

Project Setup and the Golden Rule

A few settings keep snapshot tests stable across a team:

  1. *.verified.* files go into source control. *.received.* files are listed in .gitignore and never get committed.
  2. .gitattributes pins line endings for verified files, so Windows and macOS checkouts produce identical files.
  3. A module initializer turns off automatic diff tool launching, which is useful in a classroom or on CI. Comment that line out locally if you want the diff tool to open.

.gitattributes

*.verified.txt text eol=lf working-tree-encoding=UTF-8
*.verified.xml text eol=lf working-tree-encoding=UTF-8
*.verified.json text eol=lf working-tree-encoding=UTF-8

M02.XUnitBasics.Tests/VerifySnapshotTests.cs

public static class VerifyModuleInitializer
{
[ModuleInitializer]
public static void Initialize()
{
// Do not open a diff tool (Rider, VS Code, Beyond Compare...) automatically.
// (Verify already turns this off on CI by itself.)
DiffRunner.Disabled = true;
}
}

The golden rule is the same for the hand-made version and for Verify: never approve a snapshot blindly. Approving a snapshot is a code review. If you rename every received file to verified without reading it, the test will happily lock in a bug. Read the diff, ask whether each change is intended, and only then accept it. Also keep snapshots small and focused. A snapshot of an entire page or a huge object fails for every unrelated change, and people stop reading those diffs.

Summary

  1. A snapshot test compares output with an approved *.verified.txt file and fails until a person approves any change.
  2. Remove anything that varies by machine or run: pass a culture explicitly, fix dates, and normalize line endings.
  3. Verify replaces the hand-made helper with one call, Verify(value), and names files after the test class and method.
  4. Verify serializes objects and scrubs Guid and DateTime values. Use IgnoreMember and ScrubMachineName for values it cannot detect.
  5. Commit verified files, ignore received files, and treat every approval as a code review.