📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

When would you use snapshot testing with Verify instead of writing explicit assertions?

When snapshot testing with Verify beats explicit assertions, how .verified and .received files, scrubbing and accepting changes work, and how to keep snapshots reviewable and maintainable.

Intermediate Theory Intermediate api-testing approval-testing snapshot-testing testing verify xunit

🎯 Key points

  • Verify serialises the result to {Class}.{Method}.verified.txt, committed to git
  • On a difference it writes .received.txt, fails and opens a diff tool (DiffEngine)
  • Fits large or structured output: API responses, generated code, emails, OpenAPI documents
  • Guids and dates are scrubbed by default; add ScrubMember or custom scrubbers for other volatile values
  • Accepting a change = reviewing the diff, then `dotnet verify accept` or moving received to verified; reviewed in the PR
  • Explicit assertions for the one or two values that encode a business rule
  • Risk: blind accepting turns snapshots into change detectors, not tests
  • Verify is MIT-licensed; xUnit v3 uses the Verify.XunitV3 package

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Snapshot testing, or approval testing, means: run the code, serialise the whole result, and compare it with a file a human approved earlier. In .NET the tool is Verify. The test ends with return Verify(result);. The first run writes a .received.txt file and fails. I look at it, accept it, and it becomes ClassName.MethodName.verified.txt, which I commit. On later runs any difference fails the test, writes a new received file and opens my diff tool.

I reach for it when the output is big or shaped like a document: a JSON response with twenty fields, a rendered email, the OpenAPI document, the C# a source generator emits. Writing twenty Assert.Equal lines is tedious, and people skip the fields that matter. With Verify the whole thing is checked, and the diff in the pull request shows the reviewer exactly what changed in the contract. Values that change every run get scrubbed. Verify replaces Guids and dates with Guid_1 and DateTime_1 by default, and I add ScrubMember for things like an ETag.

The mistake I see is treating snapshots as a box to tick: the test fails, someone runs accept-all and commits it without reading. Then the snapshot only tells you that something changed, not whether it's right. So I keep explicit assertions for the values that encode a rule, like 'total includes 10% GST' or 'status is 409', and use snapshots for the shape around them. Snapshots show you what changed. Assertions say what must stay true."


Snapshot or explicit assertion?

Use a snapshot when Use explicit assertions when
Output is large or nested (JSON, HTML, emails) One or two values carry the meaning
You care about the whole contract shape The rule should be readable in the test ("10% GST")
Output is generated (OpenAPI, source generators, SQL from EF Core) Output is non-deterministic and hard to scrub
You want reviewers to see contract changes in the PR diff The team won't review snapshot diffs

Working with Verify

Task How
Write a snapshot test return Verify(result); (or VerifyJson, VerifyXml)
Scrub a volatile member .ScrubMember("ETag"), or .ScrubLinesContaining("traceId")
Accept changes Diff tool "accept", or dotnet verify accept (the Verify.Tool global tool)
Keep CI clean Commit *.verified.*, add *.received.* to .gitignore. On CI, Verify detects the build server and doesn't launch diff tools.
Test HTTP or EF Core The Verify.Http and Verify.EntityFramework extensions

Cost and speed

A snapshot comparison is one serialisation plus a file read, so it costs about the same as a handful of assertions. The real cost is maintenance. Every intended change to the output means reviewing a diff, which is a good thing for public contracts and a nuisance for internal noise. Keep snapshots focused: snapshot the DTO, not the whole HttpResponseMessage with every header.

Production example

A public API with around 40 endpoints can protect its contract with one Verify test per endpoint, plus a snapshot of the OpenAPI document. Then a renamed property shows up as a one-line diff in review, not as a broken mobile client after release.

πŸ” What the interviewer is checking

Checks whether the candidate knows how snapshot testing works and can judge when it helps and when it only detects change.

Green flags

  • Explains verified and received files, scrubbing and the accept workflow.
  • Gives good fits: API responses, generated code, emails, the OpenAPI document.
  • Keeps explicit assertions for business rules.
  • Mentions reviewing snapshot diffs in pull requests and keeping received files out of git.

Red flags

  • "Snapshots replace all assertions."
  • Accepts every failure without reading it.
  • Has never dealt with volatile data such as Guids and timestamps.

πŸ“š Learn in depth

1. What approval testing is

A normal assertion encodes the expected value in the test. An approval test stores it outside the test, as a file a human approved. The test becomes "produce the output, compare it with what was approved".

first run:   result ──serialise──▢ Class.Method.received.txt ──(human accepts)──▢ Class.Method.verified.txt
later runs:  result ──serialise──▢ compare with .verified.txt
                                   β”œβ”€ same      β†’ pass
                                   └─ different β†’ write .received.txt, fail, launch diff tool

2. How Verify works

  • Naming: the file name comes from the test class and method (plus parameters for theories), so each test owns one file next to its source file.
  • Serialisation: objects are serialised with Argon, Verify's fork of Json.NET, to a stable, readable JSON-like format. Properties keep a deterministic order and default values are left out, so diffs stay small.
  • Scrubbing: before comparing, Verify replaces Guids, DateTime, DateTimeOffset and similar values with numbered placeholders (Guid_1, DateTime_1). The same Guid gets the same placeholder, so you can still see that two fields hold the same id. Extra scrubbers include ScrubMember, ScrubLinesContaining and AddScrubber.
  • Diffing: DiffEngine finds an installed diff tool (VS Code, Rider, Beyond Compare...) and opens received against verified. On a build server it detects CI and doesn't launch anything.

3. The workflow in a team

  1. A developer changes the code, and a snapshot test fails locally.
  2. They read the diff. If it's intended, they accept it, which moves the received file over the verified one.
  3. The pull request now contains the .verified.txt change. The reviewer sees the contract change line by line.
  4. CI only compares. It never accepts.

Add a .gitattributes rule such as *.verified.txt text eol=lf so Windows and Linux agents don't fail on line endings.

4. Where it fits well

  • API contracts: response bodies, ProblemDetails, the OpenAPI document from Microsoft.AspNetCore.OpenApi.
  • Generated code: incremental source generator output, verified with Verify.SourceGenerators.
  • EF Core SQL: ToQueryString() output, so an innocent LINQ change that turns a join into N+1 shows up in review.
  • Documents and messages: emails, PDFs (converted to text or images), integration events.

5. Failure modes

  • Accepting blindly: a reviewer sees 400 lines of snapshot diff and approves without reading.
  • Over-broad snapshots: snapshotting a whole response with headers and timings means every unrelated change fails the test.
  • Hidden non-determinism: dictionary ordering, culture-specific number formats and machine names make tests flaky. Fix the source or scrub it.

Try it yourself

  1. Add Verify.XunitV3 to a test project and snapshot a DTO with a Guid and a date. Look at the scrubbed output.
  2. Rename a property and watch the diff tool open. Accept it and look at the git diff.
  3. Snapshot ToQueryString() for an EF Core query, then add an Include and compare the SQL.
  4. Snapshot your API's OpenAPI document and add a new endpoint.
  5. Add *.received.* to .gitignore and run the suite with a deliberately failing snapshot on CI.

πŸ’» Code

Snapshot the shape of a quote, but assert the GST rule explicitly (xUnit v3, Verify.XunitV3).

#nullable enable
using Xunit;
using static VerifyXunit.Verifier;

namespace Quotes.Tests;

// ----- Code under test -----
public sealed record QuoteLine(string Sku, int Quantity, decimal UnitPrice);

public sealed record Quote(
    Guid Id,
    DateTimeOffset CreatedAt,
    IReadOnlyList<QuoteLine> Lines,
    decimal Subtotal,
    decimal Gst,
    decimal Total);

public static class QuoteCalculator
{
    private const decimal GstRate = 0.10m; // Australian GST

    public static Quote Create(IReadOnlyList<QuoteLine> lines, TimeProvider clock)
    {
        var subtotal = lines.Sum(l => l.Quantity * l.UnitPrice);
        var gst = Math.Round(subtotal * GstRate, 2, MidpointRounding.AwayFromZero);
        return new Quote(Guid.NewGuid(), clock.GetUtcNow(), lines, subtotal, gst, subtotal + gst);
    }
}

// ----- Tests -----
public sealed class QuoteCalculatorTests
{
    private static readonly QuoteLine[] Lines =
    [
        new("WIDGET", 3, 19.95m),
        new("GADGET", 1, 120.00m)
    ];

    // Explicit assertion: the business rule is readable in the test.
    [Fact]
    public void Gst_is_ten_percent_of_subtotal()
    {
        var quote = QuoteCalculator.Create(Lines, TimeProvider.System);

        Assert.Equal(179.85m, quote.Subtotal);
        Assert.Equal(17.99m, quote.Gst); // 17.985 rounds away from zero
    }

    // Snapshot: the whole shape, so any added, removed or renamed field shows up in review.
    // Id and CreatedAt are scrubbed automatically to Guid_1 and DateTimeOffset_1.
    [Fact]
    public Task Quote_shape_is_stable()
    {
        var quote = QuoteCalculator.Create(Lines, TimeProvider.System);
        return Verify(quote);
    }
}

The committed QuoteCalculatorTests.Quote_shape_is_stable.verified.txt:

{
  Id: Guid_1,
  CreatedAt: DateTimeOffset_1,
  Lines: [
    { Sku: WIDGET, Quantity: 3, UnitPrice: 19.95 },
    { Sku: GADGET, Quantity: 1, UnitPrice: 120.00 }
  ],
  Subtotal: 179.85,
  Gst: 17.99,
  Total: 197.84
}
# .gitignore: never commit received files
echo "*.received.*" >> .gitignore

# Accept all pending snapshots after reviewing the diffs
dotnet tool install --global verify.tool
dotnet verify accept

⚠ Common mistakes

  • Mistake: Accepting all snapshots without reading the diff. Why it is wrong: The test then only says "something changed" and can lock in a bug as the new expected output. Instead: Read each diff, and have the reviewer check .verified changes in the pull request.
  • Mistake: Snapshotting the whole HttpResponseMessage, including headers, timings and trace ids. Why it is wrong: Unrelated changes fail the test, so people start accepting blindly. Instead: Snapshot the DTO or body, and scrub what remains volatile.
  • Mistake: Using snapshots for the core business rule. Why it is wrong: The rule is buried in a file and nobody notices when it changes. Instead: Assert the rule explicitly and snapshot the shape around it.
  • Mistake: Committing .received.txt files, or not committing .verified.txt. Why it is wrong: CI either fails for everyone or has nothing to compare with. Instead: Commit verified files and gitignore received files.
  • Mistake: Leaving non-deterministic data in the output (dictionary ordering, culture-formatted numbers, machine names). Why it is wrong: The test becomes flaky across machines and agents. Instead: Sort collections, use invariant culture, and add scrubbers.
  • Mistake: Ignoring line endings. Why it is wrong: Snapshots written on Windows fail on Linux agents. Instead: Add *.verified.txt text eol=lf to .gitattributes.

πŸ› Senior insight: trade-offs

Snapshot tests are strongest at boundaries: API contracts, messages other teams consume, generated code. There, the important question is "did the contract change?", and a diff in the pull request answers it better than any assertion. Inside the domain I want readable, explicit assertions that name the rule. I check the balance by looking at how often snapshot updates get merged with no reviewer comment. If that's nearly always, the snapshots are too broad.

Verify is MIT-licensed and actively maintained, so there's no licence risk, unlike FluentAssertions, which has needed a commercial licence since version 8 in 2025.

Option When it fits Cost When not to
Verify snapshot Large or structured output, public contracts, generated code Diff review on every intended change Output you can't make deterministic
Explicit assertions One or two meaningful values More code for large objects Asserting 30 fields one by one
Snapshot + key assertions Contract shape plus a business rule Both, but small Never a bad default for important endpoints
Contract tests (Pact) Agreement between separate teams or services Broker and pipeline setup A single team owns both sides

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me