Select Page

A snapshot test compares current output with an approved example. That is useful when the output itself is a contract, such as a small customer-facing text report. It becomes less useful when every internal change rewrites a large baseline that nobody can confidently review.

This tutorial builds a small text snapshot check, introduces an arithmetic defect, and shows why accepting new output cannot establish that the calculation is correct. The complete C# console program targets .NET 10 and uses only the base class library. It demonstrates the comparison mechanism without a snapshot framework, package restore dependency, or test-runner integration.

Start with a baseline you can explain

Our report has a subtotal of 20.00, tax of 4.00, and total of 24.00. Those expected numbers are written independently in the approved text. The renderer does not generate its own expected result. In a project, keep the approved text under version control and review changes alongside the code that caused them. Here it stays inline so the whole example fits in one file.

Microsoft recommends tests that are isolated, repeatable, and focused on observable behavior. Those principles help decide what belongs in a snapshot: a stable report can be a useful boundary, while an incidental object dump can tie tests to implementation details. See Microsoft’s unit testing guidance.

Run the passing and deliberately failing comparisons

With the .NET 10 SDK installed, create a console project:

dotnet new console --name SnapshotDemo --framework net10.0

Replace its entire Program.cs with this program:

using System;
using System.Globalization;

const string approved = "Subtotal: 20.00\nTax: 4.00\nTotal: 24.00\n";
Invoice correct = Calculate(20m, 0.20m, omitTax: false);
Invoice broken = Calculate(20m, 0.20m, omitTax: true);
string correctReport = Render(correct);
string brokenReport = Render(broken);

Check("approved report matches", Matches(approved, correctReport), true);
Check("missing tax is a snapshot mismatch", Matches(approved, brokenReport), false);
Check("reapproving broken output matches", Matches(brokenReport, brokenReport), true);
Check("correct total satisfies rule", HasValidTotal(correct), true);
Check("broken total violates rule", HasValidTotal(broken), false);

string renamedReport = Render(correct, "Amount due");
Check("caption change is a snapshot mismatch", Matches(approved, renamedReport), false);
Check("caption change leaves total rule satisfied", HasValidTotal(correct), true);
Console.WriteLine("All 7 harness assertions passed.");

static Invoice Calculate(decimal subtotal, decimal rate, bool omitTax)
{
    decimal tax = subtotal * rate;
    decimal total = omitTax ? subtotal : subtotal + tax;
    return new Invoice(subtotal, tax, total);
}

static string Render(Invoice invoice, string totalCaption = "Total") =>
    "Subtotal: " + Money(invoice.Subtotal) + "\n" +
    "Tax: " + Money(invoice.Tax) + "\n" +
    totalCaption + ": " + Money(invoice.Total) + "\n";

static string Money(decimal value) =>
    value.ToString("F2", CultureInfo.InvariantCulture);

static bool Matches(string expected, string actual) =>
    string.Equals(expected, actual, StringComparison.Ordinal);

static bool HasValidTotal(Invoice invoice) =>
    invoice.Total == invoice.Subtotal + invoice.Tax;

static void Check(string name, bool actual, bool expected)
{
    if (actual != expected)
        throw new InvalidOperationException("Unexpected result: " + name);
    Console.WriteLine("PASS: " + name);
}

sealed record Invoice(decimal Subtotal, decimal Tax, decimal Total);

Run the project:

dotnet run --project SnapshotDemo

Expected stdout:

PASS: approved report matches
PASS: missing tax is a snapshot mismatch
PASS: reapproving broken output matches
PASS: correct total satisfies rule
PASS: broken total violates rule
PASS: caption change is a snapshot mismatch
PASS: caption change leaves total rule satisfied
All 7 harness assertions passed.

The harness checks seven expected outcomes and throws if any outcome differs. A line saying that a mismatch passed means the harness successfully detected the deliberately failing snapshot comparison. All seven harness assertions should pass; the faulty calculation has not been certified as correct.

The baseline uses explicit newline characters, and the renderer uses the same line ending. Decimal.ToString(format, provider) supplies the numeric format and culture; this example uses F2 with invariant culture to produce two decimal places. String.Equals with StringComparison selects the comparison rules; Ordinal makes this comparison case-sensitive and independent of the current culture. Whitespace and captions remain part of our expected output.

There is no clock, random data, file write, or external service in this fixture. Its data stays in memory, so there are no files or shared resources to clean up. It tests these report strings and arithmetic checks, without exercising a database, UI, network, or snapshot-library approval workflow.

Read what each check proves

Case Snapshot result What to learn
Correct report Matches approved text This input produced the expected report.
Total omits tax Mismatch The old baseline catches this visible regression.
Broken output becomes the baseline Match Agreement with an accepted result does not establish correctness.
Total caption becomes Amount due Mismatch A presentation change matters to this snapshot even when the amount is unchanged.

The reapproval line deliberately compares the broken report with itself. It models blindly replacing approved text with newly generated output; it is not a useful assertion to keep in an application test suite. When a snapshot changes, inspect the diff, check the intended requirement, and approve only changes you can explain. The missing tax should be repaired, not accepted.

The separate total rule rejects the broken invoice after its output has been accepted. It checks the relationship between three values instead of preserving their presentation. That rule also has limits: a wrong tax amount and a consistently wrong total could satisfy it. Keep independent assertions for the expected tax rate, rounding requirements, and boundary inputs when those are part of your application. Neither this one input nor this one invariant proves a complete invoicing system.

When to keep a snapshot, and when to use another assertion

  • Keep a small snapshot when wording and layout are requirements. A caption change should fail if users or downstream consumers depend on that caption.
  • Use focused value assertions for calculations. State the expected amount or relationship directly so a failure explains the broken rule.
  • Avoid broad snapshots whose diffs cannot be reviewed. Choose a smaller observable output instead of freezing every field in a large object graph.
  • Control unstable inputs before capturing output. Supply fixed times, identifiers, and ordering where appropriate. If a date or identifier is part of the contract, assert it separately rather than masking it away.
  • Skip a presentation snapshot when presentation is deliberately flexible. In this example, the caption change leaves the total rule satisfied. Whether it should block a release depends on whether that wording is a requirement.

A practical review question is: “If this snapshot changes, can I tell whether the new output is correct?” If the answer requires reverse-engineering a large diff, narrow the snapshot and add explicit checks for the behavior that matters.

For related C# background, see building report strings with interpolation and the methods tutorial. These explain the rendering and helper-method mechanics used around the test boundary.

Share This