Covers Verify snapshot testing in xUnit: received and verified files, snapshotting API responses, scrubbing volatile data, global settings and the review workflow in CI.
Verify serialises whatever you pass to Verify(...) and compares it with a committed .verified. file next to the test. On a mismatch it writes a .received. file and fails, so you diff and accept the new snapshot deliberately.
It shines for large outputs: API response bodies, generated code, emails, OpenAPI documents. By default it replaces Guids and DateTimes with stable placeholders like Guid_1; other volatile values are scrubbed with ScrubMembers or ignored.
In CI, mismatches must just fail; acceptance happens locally and the .verified. diff is reviewed in the pull request.
The trade-off: one line asserts a whole payload, but careless acceptance turns snapshots into rubber stamps.
"Snapshot testing means asserting on a whole serialised output instead of picking fields one by one. In .NET the standard tool is Verify, which is MIT-licensed and has adapters for xUnit, NUnit and MSTest. I call
await Verify(result); Verify serialises it to JSON-like text and compares it withTestClass.Method.verified.txtcommitted next to the test. If the file is missing or different, it writes a.received.txt, opens a diff tool locally, and fails. I look at the diff and accept it if it is what I meant.Where it pays off is wide outputs. For example, on [an integration API] we had response DTOs with 40-plus fields across nested objects. Hand-written asserts covered maybe ten of them, so a mapping change that dropped a field or changed casing slipped through. Switching those endpoint tests to snapshot the full response body through
WebApplicationFactorycaught [two contract breaks] in the first month, before consumers did. The key is scrubbing: Verify already turns Guids and DateTimes intoGuid_1,DateTime_1, keeping the relationships between values, so two references to the same id show the same placeholder. Anything else volatile, like a generated order number or an ETag, I scrub withScrubMembersorScrubLinesContaining, set once in a module initialiser.The mistake I see is treating acceptance as a formality: someone runs 'accept all', commits forty changed snapshots, and the reviewer skims past a real regression. So
.verifiedfiles are reviewed like code, CI never accepts anything, and I don't use snapshots for single business rules, where an explicit assert explains intent better. A snapshot is an assertion you approve once and then defend in review."
| Step | What happens |
|---|---|
await Verify(target) |
Target serialised (Argon, a Json.NET fork) to text |
| Compare | Against {Class}.{Method}.verified.txt |
| Match | Test passes, .received deleted |
| Mismatch or missing | .received.txt written, diff tool launched (locally), test fails |
| Accept | Copy received over verified (diff tool, Verify.Terminal, or IDE plugin) |
| Need | API |
|---|---|
| Guid / DateTime | Scrubbed by default (DontScrubGuids() / DontScrubDateTimes() to opt out) |
| Remove a property | IgnoreMember("ETag") or IgnoreMember<Order>(o => o.Version) |
| Keep property, hide value | ScrubMember("OrderNumber") / ScrubMembers(...) |
| Line-level | ScrubLinesContaining("traceId") |
| Custom | AddScrubber(sb => ...) |
| Good fit | Poor fit |
|---|---|
| API response bodies, ProblemDetails | A single calculated value |
| Generated code (source generators), OpenAPI docs | Outputs that are random by nature |
| Rendered emails, CSV exports | Teams that won't review snapshot diffs |
On [a partner API], snapshotting [about 60] endpoint responses replaced [roughly 1,500 lines] of field-by-field asserts. Each test runs in 20–40 ms with a shared factory, and the .verified.json diffs in pull requests became the place where API contract changes were discussed with the consuming team.
Checks whether the candidate can use snapshot testing productively and knows its failure modes.
Green flags
Red flags
Snapshot testing is a form of approval testing (Llewellyn Falco's ApprovalTests). Instead of writing the expected value in code, you let the system produce it, inspect it once, and approve it:
run test ─▶ serialise output ─▶ .received.txt
│
compare with .verified.txt
│ same │ different / missing
▼ ▼
pass fail + diff tool
│ human accepts
▼
.verified.txt updated, committed
By default the file is {TestClass}.{TestMethod}.verified.{ext} beside the test source file. Verify finds that path via [CallerFilePath], which is why the source path must be deterministic in builds that move files (it uses the project directory info written at build time). For [Theory] tests, parameter values are added to the name; UseParameters(...) controls this. UseDirectory("Snapshots") keeps them in a sub-folder.
Verify uses Argon (its Json.NET fork) with settings tuned for diffs: properties in declared order, default values omitted, no quotes on simple names. Dictionaries are sorted. That stability is what makes diffs small and readable. For HTTP, the Verify.Http package can snapshot an HttpResponseMessage including status and headers; VerifyJson(string) normalises raw JSON.
The default Guid scrubber replaces each distinct Guid with a counter: the first seen becomes Guid_1, the second Guid_2, and repeats keep their number. So if order.Id and lines[0].OrderId are the same value, both show Guid_1 and the snapshot still proves the relationship. DateTimes work the same way (DateTime_1). Use a fixed TimeProvider (e.g. FakeTimeProvider) when you need real dates in the snapshot.
Verify detects common CI environments (via environment variables like CI, TF_BUILD, GITHUB_ACTIONS) and doesn't launch diff tools there. The test simply fails. Uploading *.received.* files as build artefacts lets a reviewer see what changed. Never commit .received files: add *.received.* to .gitignore.
Settings that apply to every test go in a module initialiser so they run once before any test:
[ModuleInitializer] -> VerifierSettings.ScrubMembers(...), UseStrictJson(), ...
Guid_1.WebApplicationFactory and scrub a generated order number.CI=true and confirm no diff tool opens and the test fails.Verify.SourceGenerators.An xUnit v3 test that snapshots an API response through WebApplicationFactory, with global scrubbing in a module initialiser.
#nullable enable
namespace Orders.Api.Tests;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc.Testing;
using VerifyXunit; // package: Verify.XunitV3
using Xunit;
// The response contract under test (normally in the API project)
public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice);
public sealed record OrderResponse(
Guid Id, string OrderNumber, string ETag, DateTimeOffset CreatedAt,
string TrackingUrl, IReadOnlyList<OrderLine> Lines, decimal Total);
public static partial class VerifyConfig
{
[GeneratedRegex(@"trk_[A-Za-z0-9]{12}")]
private static partial Regex TrackingToken();
// Runs once per test assembly, before any test
[ModuleInitializer]
public static void Init()
{
// Guids and DateTimes are already scrubbed by default (Guid_1, DateTimeOffset_1)
// 1. Keep the property but hide a generated value: proves it exists
VerifierSettings.ScrubMember("OrderNumber"); // "ORD-20261121-8F3A" -> {Scrubbed}
// 2. Drop a property entirely: changes every write, no contract value
VerifierSettings.IgnoreMember("ETag");
// 3. Remove whole lines, e.g. ProblemDetails traceId in error snapshots
VerifierSettings.ScrubLinesContaining("traceId");
// 4. Custom scrubber for a token embedded inside a string value
VerifierSettings.AddScrubber(sb =>
{
var replaced = TrackingToken().Replace(sb.ToString(), "trk_{Scrubbed}");
sb.Clear().Append(replaced);
});
}
}
public sealed class GetOrderTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
[Fact]
public async Task GetOrder_ReturnsFullContract()
{
var ct = TestContext.Current.CancellationToken;
var client = factory.CreateClient();
var created = await client.PostAsJsonAsync("/orders",
new { lines = new[] { new { sku = "SKU-1", quantity = 2 } } }, ct);
var location = created.Headers.Location!;
// The result comes from an awaited HTTP call; Verify itself is async too
var order = await client.GetFromJsonAsync<OrderResponse>(location, ct);
// One line asserts every field; the .verified.txt file is the expectation
await Verifier.Verify(order);
}
}
The committed GetOrderTests.GetOrder_ReturnsFullContract.verified.txt then looks like this:
{
Id: Guid_1,
OrderNumber: {Scrubbed},
CreatedAt: DateTimeOffset_1,
TrackingUrl: https://track.example.com/trk_{Scrubbed},
Lines: [
{
Sku: SKU-1,
Quantity: 2,
UnitPrice: 24.50
}
],
Total: 49.00
}
# GitHub Actions: keep failure artefacts so reviewers can see what changed
- run: dotnet test --configuration Release
- if: failure()
uses: actions/upload-artifact@v4
with:
name: snapshot-mismatches
path: '**/*.received.*'
# .gitignore
*.received.*
.verified diff in the PR like code..received files. Why it is wrong: They are failure artefacts and confuse later runs and reviews. Instead: *.received.* in .gitignore; upload them as CI artefacts.ScrubMember, IgnoreMember or a custom scrubber in a module initialiser.DateTime.UtcNow in the code under test and then fighting the snapshot. Why it is wrong: Time leaks into output. Instead: Inject TimeProvider and use FakeTimeProvider in tests.Snapshots are excellent change detectors for wide contracts and weak specifications for narrow rules. I use them where the shape is the requirement (public API responses, generated code, documents sent to customers) and keep explicit asserts where the rule is the requirement. The cultural part matters more than the tool, so I make it concrete:
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Verify snapshot | Wide payloads, generated output | Review discipline, scrubbing setup | One-value rules |
| Explicit asserts | Business rules, edge cases | More code for wide objects | 40-field DTOs |
| Contract tests (Pact) | Cross-team API agreements | Broker and CI setup | Internal-only endpoints |
| OpenAPI diff in CI | Breaking-change detection on the spec | Spec must be accurate | Behaviour checks |
| Environment | Verify behaviour | What I configure |
|---|---|---|
| Developer machine | Opens diff tool on mismatch | Diff tool or IDE plugin, Verify.Terminal for bulk review |
| CI (GitHub Actions, Azure Pipelines) | Detects CI, no diff tool, test fails | Upload *.received.* as artefacts on failure |
| Linux vs Windows agents | Line endings and paths can differ | .gitattributes with *.verified.* text eol=lf, scrub machine-specific paths |
To measure value: count contract regressions caught before release, and watch for the anti-signal of PRs that touch many snapshots with no explanation.
Use snapshot testing when the output is large or structured and you care about all of it: an API response, a generated email, source generator output, an OpenAPI document. Verify serialises the result to a .verified.txt file that is committed with the code. On the next run it compares the new output and, if anything differs, writes a .received.txt file, fails the test and shows a diff.
Verify scrubs volatile values such as Guids and dates by default. When a change is intended, you review the diff and accept it, and the updated snapshot is reviewed again in the pull request.
I keep explicit assertions for the one or two values that are the business rule, such as "GST is 10%". The trade-off is that snapshots replace a lot of assertion code, but if people accept them without reading, they only detect change. They stop checking correctness.
WebApplicationFactory<Program> (package Microsoft.AspNetCore.Mvc.Testing) starts your real Program, with its middleware, routing, model binding, filters and DI, on an in-memory TestServer. CreateClient() returns an HttpClient that calls it without opening a socket.
ConfigureWebHost with builder.ConfigureTestServices(s => { s.RemoveAll<IPaymentGateway>(); s.AddSingleton<IPaymentGateway, FakeGateway>(); }). It runs after the app's own registrations, so the last one wins.AuthenticationHandler under a "Test" scheme that builds a ClaimsPrincipal from a header, so [Authorize] and policies run for real.IClassFixture), with unique or reset data per test.The trade-off: very high confidence in the HTTP contract for millisecond-level cost, but no real Kestrel, TLS or network.
How to tell it (STAR)
**S:** At [company] our partner API dropped a field after we switched to a generated mapper, and [the partner] noticed before we did. **T:** I owned the fix and making sure contract changes couldn't slip through again. **A:** I hot-fixed the mapping, then moved our partner endpoints to Verify snapshot tests of the full response body, set up scrubbing for ids, timestamps and generated reference numbers in a module initialiser, and made the API owners code owners of the snapshot files. **R:** Over the next [quarter] the snapshots flagged [three] unintended contract changes in pull requests, and we had no further partner-reported contract regressions.
Last updated 23 Nov 2026.