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

📚 Interview question

How do you use snapshot testing with Verify in a .NET project? Show how you snapshot an API response, scrub volatile values like ids and timestamps, and handle accepting changes in CI.

Covers Verify snapshot testing in xUnit: received and verified files, snapshotting API responses, scrubbing volatile data, global settings and the review workflow in CI.

Mid-Level Coding Intermediate api-testing ci-cd snapshot-testing testing verify xunit

🎯 Key points

  • Verify serialises the result, writes a .received. file and compares it with the committed .verified. file
  • First run fails by design; a human reviews and accepts the snapshot
  • Verify scrubs Guids and DateTimes to stable placeholders by default, keeping relationships between values
  • Use ScrubMember, IgnoreMember, ScrubLinesContaining or AddScrubber for other volatile values
  • Global settings go in a [ModuleInitializer] class
  • CI must fail on any mismatch and never auto-accept; Verify detects CI and skips diff tools, so publish .received files as artefacts
  • Snapshots suit large outputs (API payloads, generated code), not single business rules
  • Snapshot diffs are reviewed in pull requests and become the place to discuss contract changes with consumers

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 with TestClass.Method.verified.txt committed 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 WebApplicationFactory caught [two contract breaks] in the first month, before consumers did. The key is scrubbing: Verify already turns Guids and DateTimes into Guid_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 with ScrubMembers or ScrubLinesContaining, 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 .verified files 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."


How Verify works

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)

Scrubbing options

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 => ...)

When to use / not

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can use snapshot testing productively and knows its failure modes.

Green flags

  • Explains received vs verified files and the accept step
  • Knows default Guid/DateTime scrubbing and how to scrub other values
  • CI fails on mismatch, never accepts
  • Says when snapshots are the wrong tool

Red flags

  • "Accept all" as a normal workflow
  • Snapshots for every test including single rules
  • No plan for volatile data

📚 Learn in depth

1. The approval-testing idea

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

2. File naming and location

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.

3. Serialisation and stable output

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.

4. How scrubbing keeps relationships

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.

5. CI behaviour

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.

6. Global configuration

Settings that apply to every test go in a module initialiser so they run once before any test:

[ModuleInitializer] -> VerifierSettings.ScrubMembers(...), UseStrictJson(), ...

Try it yourself

  1. Snapshot a DTO with a Guid used twice and confirm both become Guid_1.
  2. Add a field to the DTO, run the test, and read the received/verified diff.
  3. Snapshot an endpoint response through WebApplicationFactory and scrub a generated order number.
  4. Run the suite with CI=true and confirm no diff tool opens and the test fails.
  5. Snapshot a source generator's output with Verify.SourceGenerators.

💻 Code

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.*

⚠ Common mistakes

  • Mistake: Accepting all changed snapshots without reading them. Why it is wrong: The snapshot becomes whatever the code does, regressions included. Instead: Review each .verified diff in the PR like code.
  • Mistake: Committing .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.
  • Mistake: Not scrubbing generated values (order numbers, ETags, tokens). Why it is wrong: Tests fail on every run, so people stop trusting them. Instead: ScrubMember, IgnoreMember or a custom scrubber in a module initialiser.
  • Mistake: Disabling Guid scrubbing and using random ids. Why it is wrong: Snapshots change every run. Instead: Keep the default counters, or seed fixed ids.
  • Mistake: Using 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.
  • Mistake: Snapshotting a single business rule. Why it is wrong: The intent ("orders over $200 get 10% off") is hidden in a file. Instead: An explicit assert with a descriptive test name.
  • Mistake: Letting CI auto-accept snapshots. Why it is wrong: Nothing is ever verified. Instead: CI fails on mismatch; accept only locally.

🏛 Senior insight: trade-offs

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:

  • CODEOWNERS on snapshot folders for public contracts, so the API owner must approve changes.
  • A PR template line: "Snapshots changed? Explain why each change is intended."
  • A rule that snapshot updates go in their own commit, so the diff is easy to review.
  • Consumers of a partner API are tagged on PRs that change its snapshots; the diff is the change notice.
  • Revisit in a retro if people start running "accept all": that is a sign snapshots are too broad or poorly scrubbed.
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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate is asked when snapshots beat explicit assertions Why: Checks judgement on snapshot vs explicit assertions
    How to 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.

  2. When: Candidate snapshots responses through WebApplicationFactory Why: Checks they can host the API in memory and replace services
    How to answer

    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.

    • Replace services in 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.
    • Authentication: register a test AuthenticationHandler under a "Test" scheme that builds a ClaimsPrincipal from a header, so [Authorize] and policies run for real.
    • Isolation: one factory per class (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.

🛠 Real-world problems: how you handle them

Field silently dropped from a partner API response
Situation
A .NET 10 partner API serving [a logistics customer] at [about 2M requests/day]. A refactor moved mapping from manual code to a source-generated mapper. Endpoint tests asserted on [about ten of 45] fields.
Signals
Partner support ticket: `deliveryWindow.end` missing from responses since the last release. No test failures in CI; error rate flat because the partner's client tolerated nulls.
Investigation
Compared the response JSON from the previous and current release in a staging environment; diffed the generated mapper code; confirmed the destination property name differed by casing, so the mapper skipped it. Checked the CI test report: no test touched that field.
Resolution
Hotfix: explicit mapping for the property, released within [hours]. Real fix: replaced field-by-field asserts on [60] partner-facing endpoints with Verify snapshots of full response bodies, scrubbing Guids, DateTimes and generated reference numbers.
Prevention
Snapshot tests on all partner-facing endpoints; `.verified` diffs require review from the API owner (CODEOWNERS on the Snapshots folder); mapper configured to fail on unmapped destination members; OpenAPI diff check in CI.

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.

↩ Usually asked after

More in Testing Practices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me