~/qa-guides

~/qa-guides/differential-testing

>_ Differential Testing: Practical Examples and Test Cases

Compare implementations on the same inputs with ten cases covering API responses, CSV parsing, and rounding. Includes comparison contracts, counterexamples, and an investigation record.

Test designDifferential testingTest oraclesAPI testing

Published

Short answer

Differential testing runs comparable implementations on the same effective inputs and compares their observable results under an explicit contract. A disagreement identifies something to investigate: an implementation defect, an allowed variation, changed requirements, or a problem in the test setup or comparison.

For example, send the same query against matching data snapshots in an existing API and its replacement. Compare the required response fields and business values, retaining the raw responses so that any filtering or normalization can be inspected.

William McKeeman's Differential Testing for Software describes comparisons between programs, the oracle problem, and investigation of differences. This guide develops fictional API, parser, and calculation models with ten worked cases. Their inputs, contracts, outputs, and failures are teaching examples to adapt to the product being tested.

Differential testing and related comparison techniques

Differential testing compares implementations such as an existing service and its replacement, two parsers, or two calculation routines. Define what makes them comparable before interpreting their results.

Metamorphic testing instead derives related executions through controlled input transformations and checks expected relationships between the outputs. Both techniques can help investigate behavior when calculating every individual answer is difficult, but they ask different comparison questions.

A regression test can compare a current result with a stored expectation. A differential test executes comparable implementations for the selected input. A recorded legacy response can support a regression check, but its age or origin does not establish correctness.

Agreement also has limits. Two implementations can contain the same error or depend on the same faulty adapter. Preserve independent assertions for properties the contract establishes, rather than treating a matching pair as a complete correctness verdict.

Mutation testing deliberately changes an implementation to investigate whether tests detect that change. Its examples show how to improve inputs or assertions and justify an equivalence finding when a changed version survives.

Define a comparison contract

A comparison contract records the conditions under which results may be compared and the differences that matter. It is part of the test design, not a rule inferred after inspecting an inconvenient mismatch.

Specify:

  • Target behavior: The operation and requirement version both implementations are expected to satisfy.
  • Effective input: Request or file contents, relevant records, identity and permissions, configuration, clock, and other dependencies that affect the result.
  • Observation: Response fields, parsed records, calculated amounts, rejection behavior, or another defined outcome.
  • Comparison rules: Types, field presence, record identity, ordering, multiplicity, and exactness or justified tolerance.
  • Allowed variation: Specifically identified values that may differ, with the reason and applicable conditions.
  • Independent checks: Known expected values, invariants, or small manually verified examples that can expose a shared error.

For an API replacement, the network addresses can differ while the logical operation remains comparable. Conversely, identical request bytes do not establish identical effective input if one service reads yesterday's data or applies a different permission profile.

If implementations intentionally use different representations, define a reviewed mapping that preserves the behavior being checked. Dropping identifiers or converting every value to text can erase the very distinction the test needs.

How to design and execute differential tests

1. Select implementations and state their relationship

Record which requirement each implementation claims to satisfy. An established implementation is useful comparison evidence, but a known legacy defect should not become the expected behavior of its replacement.

Identify shared dependencies as well as differences. Two APIs using the same calculation library do not provide independent evidence about that library's arithmetic. Their comparison may still reveal differences in mapping, filtering, or serialization.

Choose a comparison that answers a real change question: replacing a parser, rewriting a calculation, migrating an endpoint, or evaluating another implementation of the same specified behavior.

2. Prepare matching inputs and observation points

Use the same file bytes for parsers and the same logical dataset for service comparisons. Preserve a record of the actual inputs used, not only instructions for regenerating them.

For stateful operations, isolate the executions. Running a write against A and then running B against the already changed state creates a different test. The worked API example uses a read operation on a fixed snapshot.

Define readiness checks and restore independent cases to their required baseline. The test data design guide explains how to record related data, clocks, run ownership, and reset conditions.

3. Specify independent expectations before comparing

Write down what can be established from the contract: a required field, a known record ID, a parsed string, an expected count, or a small exact calculation.

Separate those assertions from the comparison. A pair can agree while both fail an independent check. A pair can disagree while each satisfies a different approved requirement version.

If the contract does not determine which differing result is correct, record an unresolved question. Do not choose the older implementation, the majority result, or the more convenient output solely because it is available.

4. Check the comparison mechanism itself

Retain raw results before projecting them into a common representation. Validate required structure and behavior as well as equality of selected values.

Exercise the comparator with a known meaningful difference and a known allowed variation. It should detect the first and handle the second without discarding required evidence.

Keep normalization narrow and versioned. Sorting results, filling defaults, rounding amounts, or removing fields changes the comparison. Each operation needs a reason tied to the contract and a check that it does not hide a relevant defect.

5. Record comparison and contract findings separately

Capture implementation versions, fixture identity, configuration, raw outputs, comparator version, and the exact differing observation.

Distinguish a preparation blocker from a failure during the tested operation. An unavailable fixture may prevent a valid comparison. A verified response missing a required field is evidence of a contract violation; it should not be silently discarded as an unusable pair.

When results disagree, investigate the smallest relevant difference first. Keep the broader result until the explanation has been confirmed.

Worked example 1: an API replacement with meaningful IDs

Declare the API-1 response contract

Implementations A and B expose the logical operation GET /catalog?sort=rank_asc. Both use snapshot S1, the same catalog, and equivalent read permissions. A successful execution returns HTTP 200. For S1, the complete response has two items, with no pagination.

The response requires an items array, integer total, and nonempty string requestTrace. Every item requires string id and label, integer rank, and integer stock. These are the complete allowed fields at each level in this model. IDs are unique and preserve leading zeros. Items are ordered by ascending rank.

The independently known business payload is:

IDLabelRankStock
"0007"Cable10
"7"Adapter24

The quotes identify string values; they are not part of the IDs. "0007" and "7" identify different records.

The comparator checks required fields and types, exact business values, ordered item positions, and total = 2. Only the value of requestTrace may differ between executions. Its required presence and string type are still checked.

Test case 1: allow a different request trace

  • Setup: Both implementations use API-1 and snapshot S1.
  • Input: Send the declared catalog query to each implementation.
  • Results: A returns the known business payload with trace a-17; B returns it with trace b-6.
  • Comparison: Required response checks pass. The business projection matches after excluding only the allowed trace value.
  • Interpretation: Agreement is established for this fixture, with independent IDs, stocks, ranks, and count also correct.

A comparison of response bytes could report a difference because of the trace or representation details. That does not establish a business defect. Keep the raw responses so the excluded difference remains inspectable.

Test case 2: expose an ID conversion hidden by normalization

Use the same query and snapshot. A returns IDs ["0007", "7"]. B returns ["7", "7"], while retaining the corresponding labels, ranks, stocks, and total.

The response items still contain strings, so checking only the ID type is insufficient. The comparator detects items[0].id as "0007" versus "7"; independent checks also identify the lost record identity and duplicate ID.

A comparator that converts every ID to a number would turn both ID sequences into [7, 7]. With the other values unchanged, it could report agreement and conceal the defect.

Preserve identifiers as specified by API-1. If another migration genuinely changes identifiers, define an explicit correspondence between records and verify that mapping. Numeric coercion is not such a correspondence.

Test case 3: preserve an ordering requirement

Restore S1. A returns the declared item order. B returns the same two complete records in reverse order, with ranks 2 then 1.

Membership and total still match, but the ordered comparison fails at the first item. The independently known ascending-rank requirement identifies B's output as incorrect for API-1.

Sorting both outputs before comparison would make their business projections equal and remove evidence of the ordering defect. That operation would be valid only for a comparison whose contract treats the collection as unordered.

Record the received sequence before any diagnostic reformatting. A sorted display can help inspect membership while remaining unsuitable as the acceptance comparator for this endpoint.

Test case 4: keep missing stock distinct from zero

Restore S1 again. A returns stock = 0 for Cable. B omits the stock field from that item, leaving its other values and the second item unchanged.

B violates the required structure before numeric equality is considered. A comparison that supplies a default zero for missing stock would manufacture agreement.

Check property presence before applying business defaults. API-1 also does not permit null or a numeric string in this field. A legitimate zero, an absent property, null, and "0" are different observations under this contract.

These checks complement API response test cases. Comparing implementations adds evidence about consistency; each response must still satisfy its own requirements.

Worked example 2: two CSV parsing paths

Fix the dialect and expected records

For this model, CSV-1 uses UTF-8 without a byte-order mark, comma separators, double-quoted fields, doubled quotes inside quoted fields, and CRLF record endings. The fixtures contain only ASCII characters.

RFC 4180 documents common CSV conventions, including quoting and escaped quotes. It is an Informational RFC, not a universal specification for every CSV dialect. CSV-1 explicitly selects the behavior expected here.

The input file has these four physical lines, each followed by CRLF. The code spans show the actual characters in each line:

  1. id,note
  2. 0007,"Cable, 2 m"
  3. 7,"He said ""Hi"""
  4. 0090,

Both parsing interfaces expose header names separately and return the three data records in source order. Every cell remains a string. They preserve spaces, leading zeros, and empty cells; they do not filter or deduplicate records.

The known records are:

RecordIDNote
1"0007"Cable, 2 m
2"7"He said "Hi"
3"0090"""

In the last cell, "" denotes an empty string. The final input comma separates ID from an empty second field; it does not introduce a third field.

Compare acceptance or rejection, header names, record count, field count, order, and exact string values. This is a parsing comparison. The CSV import checklist separately covers mapping, validation, and writes after parsing.

Test case 5: keep a quoted comma inside one field

  • Setup: A and B both claim CSV-1 behavior and receive the identical complete fixture.
  • Independent expectation: The first data record has exactly two cells, with note Cable, 2 m.
  • Results: A exposes that record correctly. B exposes three cells for the first data record.
  • Comparison: The field counts disagree, and B fails the independently specified two-cell result.

The different result is sufficient to investigate B's parsing path. It does not by itself prove which internal parsing function caused the split.

Do not compare only a joined display string. Joining cells again with commas could make the two- and three-cell representations look similar while hiding a structural difference.

Test case 6: compare escaped quotes as parsed data

Reduce the input to the header id,note and the record 7,"He said ""Hi""", each with CRLF. This independent fixture contains one data record.

The expected note is He said "Hi", containing one quotation mark before Hi and one after it. A exposes that value; B exposes He said ""Hi"", retaining two quotation marks at each position.

The record counts and field counts match, but the parsed string values do not. The known input convention identifies B's exposed value as incorrect for CSV-1.

Compare values at the same processing stage. The raw file's doubled quotes are syntax; the parsed note contains single quote characters. Applying another CSV unescape operation inside the comparator could hide the parsing path's defect.

Test case 7: detect agreement between two incorrect paths

Return to the complete four-line fixture. In this counterexample, both exposed parsing paths share an adapter that discards records whose note is empty.

A and B each return only the first two records. Their headers, record order, and remaining values agree, so an equality comparison passes.

The independent expectation still requires three records, including ID "0090" with an empty note. Both exposed paths fail that expectation. The defect in this example is in their shared adapter; the agreement does not establish whether either underlying parser is wrong.

Keep the compared boundary explicit. Comparing two library names is not independent evidence if both observations pass through the same transformation that removes relevant data.

Worked example 3: calculations with different rounding stages

State the arithmetic rules before selecting a reference

The fictional calculation accepts 1 through 20 line amounts, each an integer from 0 through 10000 minor units. It applies a fixed 10% discount. There are no other charges or adjustments.

Contract CALC-1 calculates each line's discount, rounds it to an integer minor unit using half-up rounding, then sums the rounded discounts. Net amount equals the sum of line amounts minus that discount total.

For these nonnegative inputs, a line discount can be calculated as floor((amount + 5) / 10). For amounts 4, 5, and 6, the rounded discounts are respectively 0, 1, and 1.

Contract CALC-2, used later for an intentional requirement change, first sums the amounts and rounds the 10% discount once. These are example product rules, not universal financial policies.

The independently calculated results are:

AmountsCALC-1 discountCALC-2 discountCALC-1 netCALC-2 net
[10, 20]332727
[5, 5, 5]321213

Use exact integer observations for these contracts. A one-unit tolerance would discard a meaningful difference rather than account for an unspecified display effect.

Test case 8: observe agreement on a nondiscriminating fixture

Both implementations claim CALC-1. A rounds each line before summing; B incorrectly sums before rounding.

For input [10, 20], A computes discounts 1 + 2 = 3. B calculates 10% of 30 and also returns 3. Both report net 27.

The comparison and the known expected values pass for this fixture. However, the chosen amounts do not distinguish the rounding stages. The observation cannot establish that B implements CALC-1 correctly for other supported inputs.

Choose additional inputs for the specific behavior that could differ, rather than merely running more amounts with discounts that are already whole units.

Test case 9: expose the wrong rounding stage

Keep CALC-1 as the required contract for both implementations and use [5, 5, 5].

  • Independent CALC-1 result: Each line's unrounded discount is 0.5, rounded to 1; total discount is 3, and net is 15 - 3 = 12.
  • A result: Discount 3, net 12.
  • B result: The unrounded order discount is 1.5, rounded to 2; net is 15 - 2 = 13.
  • Interpretation: The comparison disagrees, and the independent arithmetic identifies B's result as a CALC-1 violation.

Do not increase the tolerance or round the net again to make the results match. The discrepancy comes from the stage at which a specified rounding rule is applied.

Retain the input line amounts and required contract with the results. Recording only totals 12 and 13 loses the information needed to reproduce the distinction.

Test case 10: recognize an approved requirement change

Now the replacement intentionally targets CALC-2, with an approved change from line rounding to order rounding. A still implements CALC-1; B targets CALC-2.

For [5, 5, 5], the observed outputs remain discount 3, net 12 from A and discount 2, net 13 from B. The difference is numerically identical to case 9, but the requirement versions are different.

Record the approved migration expectation: A matches the known CALC-1 result, and B matches the known CALC-2 result. This pair does not demonstrate equivalence under CALC-1; it verifies the declared change for the selected input.

Keep that exception specific to the changed rule and version. It does not approve every future calculation mismatch or allow other fields to differ without investigation.

Classify the evidence without turning agreement into certainty

Keep the comparison result and independent contract evidence as separate observations:

SituationContract evidenceRecorded conclusion
Agreement with anchorBoth match the known resultAgreement for this fixture
Shared failureMatching outputs violate the known resultInvestigate both exposed paths
Unexplained differenceCorrectness is not establishedInvestigate before approval
Approved changeEach matches its declared versionRecord the specific expected delta
Unready setupRequired starting conditions are absentRepair setup and repeat

A mismatch can be a useful discovery before its cause is known. Preserve that distinction in the report. An unexplained difference should not silently become an approved variation merely because the existing implementation produces it.

Likewise, keep shared contract failures visible even when the equality comparison passes. In case 7, the independent missing-record assertion supplies the failure evidence.

Handle rejections, crashes, and timeouts explicitly

Record how each execution ended before comparing business values: an accepted result, a specified rejection, a crash, or a timeout. These outcomes are not interchangeable even when their displayed text is empty.

For CSV-1, an unterminated quoted field such as 7,"unfinished can be a declared invalid fixture. Two different diagnostic messages may both satisfy its required rejection. Successful output containing zero records is a different outcome and must not be normalized into the same result.

For the valid API fixture, an internal error in both implementations would not establish correct behavior. The known expectation is a successful catalog response. Preserve both failures even if an error-category comparison finds them identical.

Separate the test's observation budget from a product requirement. If a harness stops waiting after its configured interval, record that limit and the available evidence. It does not automatically establish a violation of an unspecified response-time target.

An incomplete peer result can prevent business-value comparison while still providing evidence worth investigating. Conversely, a failed setup connection does not demonstrate what the product would have returned for a ready fixture.

Expand the input set without losing its meaning

Define the shared declared input scope before generating more cases. A feature intentionally outside B's scope does not provide an ordinary equivalence case against B. Record that capability difference and test each implementation's declared behavior separately. If both promise the feature, B's inability to perform it is evidence to investigate, rather than a reason to exclude the input.

Add inputs for distinctions that matter to the comparator: required zero values, ordered results, quoting, empty fields, or rounding stages. Randomly generating more ordinary values does not guarantee that those distinctions are reached.

Validate generated fixtures at the intended boundary. Filtering out every input rejected by one implementation could remove exactly the disagreements the test was meant to investigate. Keep deliberate rejection cases distinguishable from accidentally invalid preparation.

For generated inputs, retain the actual failing input and generation context. A seed alone may not reproduce the run after generator versions, execution order, configuration, or dependencies change.

Also define reporting denominators. Consider an illustrative run with 25 attempted pairs: five cannot start because their fixture is unavailable, and 20 produce usable comparisons. Of those 20, 18 agree and two differ. One agreeing pair nevertheless violates a known anchor.

The agreement rate is 18 / 20 = 90% among completed comparisons. It excludes five setup blockers and includes a known shared failure. It is not a percentage of correct behavior or coverage of the input domain. Report independent contract failures separately because they can overlap both matching and differing pairs.

Reduce a useful disagreement and preserve it for regression

After preserving the original run, simplify the input while retaining the behavior under investigation. Re-execute both implementations and the relevant independent checks after each change.

For API case 2, create a reduced snapshot S1-small containing the Cable record only. A exposes ID "0007" and B exposes "7"; the identity mismatch remains. Each response now has total 1.

This reduced case demonstrates the ID change, but it no longer demonstrates duplicate IDs because only one record remains. Keep the original two-record case if duplicate behavior is part of the reported problem.

Do not convert the IDs to numbers while reducing the fixture: that would remove the distinction being investigated. Similarly, do not remove a state prerequisite merely because the remaining input looks shorter.

With a larger snapshot, try removing records in groups. Keep a smaller snapshot when both implementations still reach the ID check and produce the same mismatch as before. The delta debugging walkthrough shows how to choose the next group and record trials that cannot reach the check.

Once the required behavior is resolved, preserve an independently reviewed expectation for a regression test. Record the necessary fixture and observation even if the old implementation will soon be retired.

A reusable differential test case and investigation record

Use a compact record with enough information to replay and judge the comparison:

  • Identity and purpose: Case ID and the behavior being compared.
  • Targets: Implementation builds, requirement versions, and relevant shared dependencies.
  • Setup and input: Concrete request or file, dataset identity, configuration, and readiness evidence.
  • Comparison contract: Required observations, allowed variation, comparator version, and independent assertions.
  • Results: Raw A and B outputs, the exact comparison difference, and separate contract findings.
  • Resolution: Defect, approved variation, unresolved question, or setup blocker, with the supporting reason.
  • Replay and maintenance: Minimal reproducer, reset needs, and the retained regression expectation.

A filled record for case 2 is:

  • Case: D-API-02, preserve string record identity during API replacement.
  • Targets: Fictional builds A-17 and B-6, both claiming API-1.
  • Setup: Snapshot S1 with Cable and Adapter, equivalent catalog read permissions, no writes during the comparison.
  • Input: GET /catalog?sort=rank_asc against each target.
  • Comparison: cmp-api-v1 checks required structure and ordered business fields; only trace values may differ.
  • Raw observation: A IDs are ["0007", "7"]; B IDs are ["7", "7"], with the known labels, ranks, stocks, and total otherwise retained.
  • Difference: items[0].id is "0007" in A and "7" in B.
  • Independent evidence: S1 requires two distinct string IDs; B loses Cable's identity and duplicates Adapter's ID.
  • Resolution: B's exposed result violates API-1. The faulty numeric-normalization comparator must also be corrected if it was used.
  • Retained cases: The original fixture proves duplicate output IDs; the one-record reduction isolates the lost leading zeros.

The record describes an invented finding. A real execution must include its actual outputs, versions, and readiness evidence, rather than copying the example's labels as proof.

FAQ

Yes. A tester can run a small fixed fixture through two exposed interfaces and inspect the same declared observations. Automation helps repeat larger input sets and retain differences, but it does not decide which behaviors should be equivalent. Both approaches need controlled setup and a trustworthy comparison rule.

No. Sequential runs can be compared when the relevant inputs, state, and configuration remain controlled. Simultaneous execution also does not guarantee that two services read the same data version. Use a verified snapshot or restored fixture and record the observation point required by the contract.

Ready to turn this guide into a working QA project with statuses, comments, and CSV export?