Golden Master Testing for Financial Calculations in .NET
Regression testing for financial calculations: compare results across commits, diff with tolerances, handle decimal rounding, and catch one-cent errors in CI.
By Victor Sanchez
Regression testing financial calculations is where unit tests stop being enough. A refactor, a framework upgrade or a new rounding helper can shift an interest amount by one cent on one loan out of ten thousand, and no hand-written assertion will notice. Before each release of the money-handling applications we maintain, we compare the results of the financial calculations across commits. This post explains the technique we use: golden-master testing.
What is golden-master testing?
A golden master (also called a characterization or snapshot test) records the output of the current, trusted version of the system for a large set of inputs. The new version runs the same inputs, and the two outputs are diffed. You don't assert what the result should be; you assert that it did not change unless you meant it to.
That makes it ideal for legacy calculations whose rules nobody can fully specify anymore, and for migrations such as the ones in our .NET Framework to modern .NET playbook, where the only acceptable result is "the same numbers".
How to build a golden master for financial calculations
1. Build a representative input set
Start from anonymized production data, then add edge cases on purpose: zero and maximum rates, one-period and very long terms, leap years, month-end start dates, grace periods and early payoffs. Keep the file in the repository so every run uses exactly the same inputs.
2. Write a deterministic runner
The runner feeds every case to the real calculation code and writes one line per result. Sort the cases and format numbers with the invariant culture, so the output is identical on every machine:
// tools/GoldenMaster.Runner/Program.cs
using System.Globalization;
using System.Text.Json;
var cases = JsonSerializer.Deserialize<List<LoanCase>>(File.ReadAllText(args[0]))!;
var calculator = new AmortizationCalculator(); // the code under test
using var writer = new StreamWriter(args[1]);
foreach (var c in cases.OrderBy(c => c.CaseId, StringComparer.Ordinal))
{
foreach (var row in calculator.Build(c.Principal, c.AnnualRate, c.Months, c.StartDate))
{
// Invariant culture: the output must not depend on the machine's locale
writer.WriteLine(string.Join('|',
c.CaseId,
row.Period.ToString(CultureInfo.InvariantCulture),
row.Interest.ToString(CultureInfo.InvariantCulture),
row.Principal.ToString(CultureInfo.InvariantCulture),
row.Balance.ToString(CultureInfo.InvariantCulture)));
}
}3. Diff with explicit tolerances
Compare line by line, by key, and report every field that moved:
// tools/GoldenMaster.Compare/Differ.cs
public static IEnumerable<string> Diff(string[] baseline, string[] candidate, decimal tolerance)
{
if (baseline.Length != candidate.Length)
yield return $"Row count changed: {baseline.Length} -> {candidate.Length}";
for (var i = 0; i < Math.Min(baseline.Length, candidate.Length); i++)
{
var b = baseline[i].Split('|');
var c = candidate[i].Split('|');
if (b[0] != c[0] || b[1] != c[1])
{
yield return $"Row {i}: key mismatch {b[0]}/{b[1]} vs {c[0]}/{c[1]}";
continue;
}
for (var f = 2; f < b.Length; f++)
{
var delta = Math.Abs(decimal.Parse(b[f], CultureInfo.InvariantCulture)
- decimal.Parse(c[f], CultureInfo.InvariantCulture));
if (delta > tolerance)
yield return $"{b[0]} period {b[1]} field {f}: {b[f]} -> {c[f]} (delta {delta})";
}
}
}Choose the tolerance per field, not globally. Amounts that are stored or shown to customers are already rounded to cents, so their tolerance should be zero. A small tolerance only makes sense for intermediate values such as unrounded rates, and it must be written down and justified.
4. Run both commits in CI before the release
Use git worktree to check out the last released commit next to the candidate, run the runner on both, and fail the pipeline if anything differs:
#!/usr/bin/env bash
set -euo pipefail
BASE=${1:-origin/main} # last released commit
git worktree add ../baseline "$BASE"
dotnet run -c Release --project ../baseline/tools/GoldenMaster.Runner -- cases.json baseline.txt
dotnet run -c Release --project tools/GoldenMaster.Runner -- cases.json candidate.txt
# Non-zero exit code if any difference exceeds the tolerance
dotnet run -c Release --project tools/GoldenMaster.Compare -- baseline.txt candidate.txt --tolerance 0When a change is intentional (a new regulation, a fixed bug), the diff is not ignored. It is attached to the pull request, reviewed by someone who understands the business rule, and the baseline moves forward only after approval. The same discipline applies to AI-assisted changes, as we describe in our checklist for reviewing AI-generated code.
How to handle decimal precision and rounding
Most surprises we have found come from a handful of numeric details:
Math.Round(2.345m, 2); // 2.34 (default: to even)
Math.Round(2.345m, 2, MidpointRounding.AwayFromZero); // 2.35
0.1 + 0.2 == 0.3; // false (double)
0.1m + 0.2m == 0.3m; // true (decimal)- Use
decimalfor money, neverdouble. Binary floating point cannot represent most decimal fractions exactly. - Make rounding explicit. .NET rounds to even by default, while many business rules expect away from zero. Write the
MidpointRoundingmode in the code, every time. - Round at the same step. Rounding each installment and rounding only the total give different results. A refactor that moves the rounding step changes numbers.
- Watch the scale.
decimalkeeps trailing zeros (1.10mprints as1.10), so compare parsed values, not raw strings.
What are the common pitfalls?
- Hidden non-determinism.
DateTime.Now, time zones, unordered dictionaries or parallel loops make the output change between runs. Inject the clock and sort everything. - Tolerances that grow. Raising the tolerance to make the pipeline green hides real regressions.
- Too few cases. Ten happy-path loans prove very little. Volume and edge cases are what catch one-cent errors.
- Baselines updated by default. If anyone can overwrite the golden master without review, the test no longer protects anything.
- Testing through the UI. Call the calculation code directly; it is faster and far less flaky.
Checklist
- Input set includes anonymized real data and deliberate edge cases.
- Runner output is sorted and culture-invariant.
- Tolerances are defined per field; money fields use zero.
- All money uses
decimalwith an explicitMidpointRounding. - CI compares the candidate against the last released commit.
- Every intentional difference is reviewed and approved before the baseline moves.
Key takeaways
- Golden-master tests assert that results did not change, which is exactly what a refactor or migration needs.
- Determinism comes first: fixed inputs, sorted output, invariant formatting, injected clock.
- Zero tolerance for money; documented tolerances for everything else.
- Run it in CI against the last release, and treat every diff as a review item.
If you are also restructuring the calculation code, see how we extract rules safely in Clean Architecture and DDD in legacy code.
Sources
- Math.Round method (Microsoft Learn)
- MidpointRounding enum (Microsoft Learn)
- Floating-point numeric types in C#
- Testing in .NET
- git worktree documentation
Need help making financial calculations safe to change?
Santhor modernizes legacy .NET systems, fixes performance problems and bugs in existing applications, and builds new software from scratch. We are based in Costa Rica and work nearshore with teams in the U.S. and Latin America. We can set up a golden-master safety net before your next release. Tell us about your project.