~/qa-guides

~/qa-guides/metamorphic-testing

>_ Metamorphic Testing: Practical Examples and Test Cases

Derive follow-up tests from input transformations and expected output relationships. Includes three worked models, nine test cases, and counterexamples that expose weak checks.

Test designMetamorphic relationsTest oraclesAPI testing

Published

Short answer

Metamorphic testing derives follow-up tests from a source test by changing inputs in a controlled way and checking the expected relationship between results. A metamorphic relation, or MR, states how an input transformation should preserve or change an observable output.

For example, permuting the input to a deterministic numeric sorter should preserve its sorted output, including repeated values. The test compares related executions instead of relying only on a separately calculated answer for each generated input.

The ISTQB Test Analyst syllabus, section 3.3.2, describes source tests, follow-up tests, relations, and joint evaluation. The three worked models below use deliberately small fixtures to make their assumptions and calculations inspectable. They are invented contracts to adapt to the product being tested.

Why compare related executions?

A test oracle is the basis for deciding whether a test result is correct. For a small calculation, the oracle may be a manually checked value. For a large result set or complex computation, predicting every correct output can be expensive or difficult.

A Survey on Metamorphic Testing, by Segura and colleagues, discusses this oracle problem and the use of relations with applicability conditions. A valid relation can expose an inconsistency across executions even when their individual correct outputs are unavailable.

The relation still needs a trustworthy basis. "These outputs should match" is an expectation that must follow from the feature's behavior, not a conclusion drawn because two current outputs happen to match. A successful comparison establishes only that the selected relation held for those executions.

Pairwise testing answers a different design question: which input combinations exercise required pairs of parameter values? Metamorphic testing defines how related inputs should constrain their outputs. A pairwise-selected configuration can supply a source test, but pair coverage does not establish that a metamorphic relation is valid.

Describe a metamorphic relation precisely

Record four connected elements before execution:

  • Source case: The input, relevant system state, configuration, and observation point for the starting execution.
  • Transformation: The exact change used to construct the follow-up case, including any intended fixture changes.
  • Output relation: The equality, subset, multiplicity, arithmetic, or other property to evaluate across results.
  • Applicability: The conditions under which that transformation and comparison are justified.

A compact notation is R(f(x), f(T(x))): run behavior f on source input x and transformed input T(x), then evaluate relation R over the results. The notation describes a test structure, not a claim that every behavior is a stateless function.

For an API, the effective input can include the dataset, permissions, filters, clock, and configuration. State which of these changes intentionally and which must remain controlled. Adding a record to a fixture is a transformation of state; merely repeating a request while unrelated records change does not create a controlled comparison.

Define the compared output explicitly. An HTTP response can include result IDs, totals, timestamps, timing data, and links. A relation about matching record IDs does not require every byte of the response to be identical.

How to design and execute metamorphic tests

1. Derive the property from the contract

Identify behavior that should remain invariant or change predictably. Useful questions include what happens when inputs are reordered, a restriction is added, independent records are copied, or all measurements are scaled.

Explain why the property should hold for this feature. Reordering independent measurements preserves their sum; reordering updates to the same record may change a last-write-wins result. Similar-looking transformations can have different meanings in different contracts.

Review the proposed relation with someone who understands the behavior when the rule is uncertain. Preserve an unresolved relation as a hypothesis to clarify, rather than using it immediately to declare product failures.

2. Choose source data that can expose a difference

Use varied values, distinct IDs, and data that exercises the relation. A filter-narrowing case needs records that should remain and records that the added restriction should remove. A sorter needs repeated values if multiplicity is part of the risk.

Avoid transformations that do nothing for the selected source. Multiplying by 1 or adding 0 may be valid, but those cases provide little evidence about how the behavior responds to the transformation. Retain such cases only when they investigate a distinct requirement.

Check the transformed input's validity as well. If adding 10 pushes a value outside the accepted range, the original relation may no longer apply. Expected rejection behavior would need its own test design.

3. Control state and construct the follow-up case

Record the build, configuration, identities, and fixtures used by both executions. Restore the source fixture between independent cases, and retain the actual generated follow-up data.

If the transformation intentionally changes the dataset, preserve references to both snapshots and their intended difference. Wait for a documented observation point that confirms the new fixture is available before interpreting a result from it.

For generated tests, record enough information to reproduce the transformation. This can include the actual permutation, new record IDs, scaling factor, or random seed. The input pair remains important evidence even when the generator can run again.

4. Compare at the level the relation requires

An ordered sequence, a set, and a multiset are different comparison units. A set records membership. A multiset also records how many times each element occurs. A sequence additionally records order.

Choose the unit from the expectation. Comparing sets can hide dropped duplicates in a numeric sorter. Comparing complete response order can create false failures when a filter contract guarantees membership but permits different ordering.

Use known small examples and independent assertions alongside relations when available. They help detect implementations that satisfy the selected relationship while still returning incorrect results.

5. Evaluate the evidence and preserve the investigation

A relation violation calls for checking the contract, transformation, environment, and observations. If those are valid and comparable, at least one involved execution disagrees with the expected behavior. The violated relation alone may not identify which execution or internal component is wrong.

When a prerequisite is missing, record the result as inconclusive or blocked according to the team's workflow. A stale search index, invalid follow-up input, or unknown precision rule can prevent evaluation of the intended relation.

Keep the source and follow-up evidence together. Reporting only the second response loses the baseline that explains why the relationship failed.

Worked example 1: numeric sorting

Declare the sorting contract

The example sorter accepts nonempty lists of 1 to 100 integers, each from 0 to 100 inclusive. It returns those values in ascending order and preserves every occurrence. It is deterministic and adds no extra elements.

Use source input x = [7, 2, 2, 5]. Its manually checked ascending output is [2, 2, 5, 7]. That known answer can serve as an anchor while the relations generate additional cases.

Test case 1: permute the input

  • Relation S-1: Permuting the input preserves the complete sorted output sequence.
  • Source: Run the sorter with [7, 2, 2, 5] and retain its result.
  • Follow-up: Run it with [2, 7, 5, 2], which contains the same values and occurrence counts.
  • Comparison: The two result sequences must be equal. Under this fixture, both correct results are [2, 2, 5, 7].
  • Independent observations: Each result must have four elements and preserve two occurrences of 2, one of 5, and one of 7. Check the declared ascending direction as well.

A sorter that drops duplicates could return [2, 5, 7] for both executions. The sequence-equality relation would pass, while the independent occurrence check would fail. This is why the comparison unit and additional assertions matter.

Test case 2: add a constant to every value

  • Relation S-2: Adding 10 to every valid input value adds 10 to each corresponding sorted output value.
  • Source: Restore the original source input [7, 2, 2, 5] and retain its result.
  • Follow-up: Use [17, 12, 12, 15]. All values remain inside the accepted domain.
  • Comparison: The follow-up result must equal the source result with 10 added element by element. For correct executions, [2, 2, 5, 7] becomes [12, 12, 15, 17].
  • Independent observations: The result length remains four, and the input transformation preserves the source positions before sorting.

A program returning the same fixed list for every input might pass S-1, including the source anchor by coincidence. It would fail this nonzero-shift relation. Changing the constant creates further follow-ups only while every transformed value remains valid.

Test case 3: duplicate the input list

  • Relation S-3: Concatenating the input with itself doubles every output value's occurrence count.
  • Source: Use [7, 2, 2, 5].
  • Follow-up: Use [7, 2, 2, 5, 7, 2, 2, 5], with eight elements inside the supported list-size limit.
  • Comparison: The follow-up output's multiplicities must be twice those of the source output. Both outputs must still satisfy the sorting contract.
  • Known fixture result: The correct follow-up sequence is [2, 2, 2, 2, 5, 5, 7, 7].

The expected multiplicities are:

ValueSource countFollow-up count
224
512
712

Comparing only distinct values would miss the difference between three, four, and eight returned elements. Check both multiplicity and the ordering behavior relevant to the test.

What these sorting relations still cannot establish

A descending sorter can satisfy S-1, S-2, and S-3: input order does not affect its result, adding 10 shifts its output, and duplicating inputs doubles multiplicities. It still violates the required ascending direction. The known source answer or an independent ascending-order assertion exposes that defect.

For records with tied sort values, review the contract before transferring S-1. A stable sort may preserve tied records' input order, so permuting the input can legitimately change their final relative order. Full sequence equality needs an appropriate deterministic tie-break rule; otherwise compare the guaranteed properties. The product search and filter testing checklist covers the wider user-facing search and sorting workflow.

Worked example 2: filtered API results

Declare the dataset and comparison scope

This example endpoint returns every matching record from a controlled snapshot. Optional Region and Status predicates combine with AND. Every record has one current status, either Open or Closed, and appears at most once in a result. There is no ranking, pagination, or result truncation in this model.

Use dataset D0:

IDRegionStatus
I-01EastOpen
I-02EastClosed
I-03WestOpen
I-04WestClosed
I-05EastOpen

I-01 and I-05 have the same filter values but remain distinct records. Matching them by field values alone would hide identity or duplication defects.

Compare ID membership and occurrence counts, together with the matching-result count. Do not require response timestamps or presentation order to match. Keep the same build, account, visibility rules, and filter semantics across the related executions.

Test case 4: add an AND restriction

  • Relation F-1: Adding a Region restriction to a Status query cannot introduce a record outside the original result.
  • Source: On D0, query Open records. The correct fixture result contains I-01, I-03, and I-05, with count 3.
  • Follow-up: On the same snapshot, query Open AND East. The correct result contains I-01 and I-05, with count 2.
  • Comparison: Every follow-up ID must occur in the source result, with no increased multiplicity. The filtered count cannot exceed the source count.
  • Known fixture checks: I-01 and I-05 remain; I-03 is removed. Each returned record must satisfy the predicates.

The general relation is a subset relationship, not a universal requirement for a strictly smaller result. Another dataset might already contain only East records. This fixture deliberately includes a removable record so the narrower behavior is observable.

An implementation that ignores the Region predicate could return the original three IDs again. It would pass the subset relation while failing the specific predicate and fixture checks. A shrinking count alone also cannot establish that the retained IDs are correct.

Test case 5: add a record that cannot match

  • Relation F-2: Adding a new Closed record preserves the complete result of an Open-only query.
  • Source: Query Open on D0 and retain the IDs and matching count.
  • Transformation: Create dataset D1 by adding only I-06, with Region West and Status Closed. Preserve all existing records.
  • Readiness check: Verify that D1 is available to the queried system and that the added ID is visible in an unfiltered lookup before evaluating the follow-up.
  • Follow-up and comparison: Query Open on D1. Its IDs and their occurrence counts must match the D0 Open result, and its matching count remains 3.

The total collection size changes from 5 to 6. An unfiltered total or a facet describing Closed records can therefore change legitimately. Comparing the entire response object would assert more than this relation justifies.

Restore D0 before another independent case. This test intentionally compares different datasets with one declared difference; uncontrolled changes to unrelated records would make the comparison ambiguous.

Test case 6: partition and recombine results

  • Relation F-3: For this two-status model, Open and Closed results are disjoint and together contain exactly the unfiltered result.
  • Source: On restored D0, query all records without a Status filter. The fixture contains all five IDs.
  • Follow-ups: Query Open and Closed separately. The expected fixture groups are I-01, I-03, I-05 and I-02, I-04.
  • Comparison: The groups have no shared IDs, their combined ID occurrences equal the unfiltered result, and their matching counts sum to 5.
  • Applicability: Both queries use the same snapshot and visibility rules; every source record belongs to exactly one of the two declared statuses.

This relation uses one source execution and two follow-up executions. A metamorphic test procedure can require more than a single pair of responses.

If the product supports additional statuses, the two groups are no longer an exhaustive partition. Update the relation or include the missing groups before interpreting a violation. Do not silently treat an assumption about a small fixture as a universal business rule.

Avoid false confidence from empty or partial results

A broken endpoint that always returns an empty result can satisfy F-1, F-2, and F-3. Empty results are subsets of each other, adding a nonmatching record changes nothing, and two empty groups recombine into an empty unfiltered result. The known positive fixture, including the expected presence of I-01, exposes the defect.

For a real paginated endpoint, obtain the complete comparison population under a consistent snapshot or use a relation designed for its actual pagination contract. One page can lose an item to another page even when the complete set is correct. The API pagination testing checklist covers those traversal and consistency concerns.

Worked example 3: totals and arithmetic means

Declare the aggregation contract

The example function processes from 1 to 1,000 independent observations. Each has a distinct ID and an integer duration from 0 to 1,000 milliseconds inclusive. Every supplied observation contributes once; equal duration values do not make two distinct observations duplicates.

The result contains the count, total duration, and arithmetic mean. Totals and counts are exact integers. Use the declared numeric precision when comparing the mean; the main fixtures below have whole-number means to keep their expected results simple.

Source dataset A0 contains:

IDDuration in ms
M-1100
M-2250
M-3400

The independently calculated source result is count 3, total 750 milliseconds, and mean 250 milliseconds. Every case below starts from a fresh copy of A0. No grouping, time-window filtering, or per-record rounding is part of this model.

Test case 7: scale every duration

  • Relation A-1: Multiplying every duration by 2 doubles the total and mean while preserving the count.
  • Source: Execute aggregation on A0 and retain all three result fields.
  • Follow-up: Preserve the IDs and use durations 200, 500, and 800 milliseconds. All transformed values remain in the accepted domain.
  • Comparison: Follow-up count equals source count; follow-up total equals twice source total; follow-up mean equals twice source mean, evaluated under the numeric contract.
  • Known fixture result: Count 3, total 1,500 milliseconds, and mean 500 milliseconds.

This transformation would need review if the product capped durations, rounded each record before aggregation, or included only observations under a threshold. In those contracts, scaling might change eligibility or precision effects as well as the numeric values.

Test case 8: copy independent observations with fresh IDs

  • Relation A-2: Adding one independent copy of every observation doubles the count and total while preserving the arithmetic mean.
  • Source: Execute aggregation on restored A0.
  • Follow-up: Keep M-1 through M-3 and add M-4, M-5, and M-6 with durations 100, 250, and 400 milliseconds respectively.
  • Comparison: Follow-up count is twice source count; follow-up total is twice source total; the mean is unchanged.
  • Known fixture result: Count 6, total 1,500 milliseconds, and mean 250 milliseconds.

Fresh IDs matter. Repeating the original IDs could invoke a valid deduplication or update policy in another product, which would invalidate the claimed input transformation. Confirm that all six independent records are eligible for this aggregation before interpreting its output.

Test case 9: add a fixed duration to every observation

  • Relation A-3: Adding 50 milliseconds to every duration preserves the count, adds 50 * sourceCount to the total, and adds 50 milliseconds to the mean.
  • Source: Execute aggregation on restored A0.
  • Follow-up: Preserve the IDs and use durations 150, 300, and 450 milliseconds.
  • Comparison: The count remains unchanged; the total increases by 150 milliseconds for this three-record source; the mean increases by 50 milliseconds.
  • Known fixture result: Count 3, total 900 milliseconds, and mean 300 milliseconds.

The three transformations have different effects:

DatasetCountTotal in msMean in ms
A03750250
Scaled31500500
Copied61500250
Shifted3900300

Scaling and copying produce the same total for this fixture but have different counts and means. Comparing only the total would discard that distinction. Keep all fields required by the selected relation.

A wrong aggregator can satisfy all three relations

Consider an incorrect implementation that returns the number of observations, takes the first duration as the mean, and calculates its reported total as count * firstDuration.

For A0, it returns count 3, total 300, and mean 100. Those values are wrong, but the three relations still hold:

  • Scaling produces count 3, total 600, and mean 200. The reported total and mean both double.
  • Copying produces count 6, total 600, and mean 100. Count and total double, while the mean stays unchanged.
  • Shifting produces count 3, total 450, and mean 150. The reported total increases by 3 * 50, and the mean increases by 50.

The known A0 anchor exposes the incorrect source total and mean. A separate permutation relation would also expose this particular implementation when a different-valued observation is moved to the first position. These observations show why several passing relations can leave a significant defect undetected.

Source data matters here too. If every source duration were 250, selecting the first value would happen to give the correct mean. Varied fixtures help distinguish the intended computation from plausible incorrect ones.

Account for rounding and representation

Apply a relation to the output representation it was derived for. Exact arithmetic on raw quantities does not automatically produce exact equalities between independently rounded displays.

For a separate valid fixture with durations 10, 10, and 20 milliseconds, the mathematical mean is about 13.333333 milliseconds. If a display rounds to the nearest 0.01 millisecond, it shows 13.33. Scaling the inputs by 2 gives a mean of about 26.666667, displayed as 26.67.

Twice the first displayed value is 26.66, which differs from 26.67. A check requiring exact equality between those displayed values would fail despite correct rounding in both executions.

Derive any tolerance from the declared representation. Under this specific rounding-only contract, each display has at most 0.005 millisecond absolute rounding error. The difference between the follow-up display and twice the source display is therefore bounded by 0.005 + 2 * 0.005 = 0.015 millisecond. Other approximation or conversion stages would require their own analysis.

Use raw values or exact total/count relationships when the product exposes them and they match the test objective. Do not invent a generous tolerance merely to make a relation pass; it could hide the discrepancy the test should investigate.

A reusable metamorphic test case template

Record enough information to reconstruct both the data transformation and the comparison:

  • Identity and purpose: Case ID, relation ID, and the requirement or property being investigated.
  • Source context: Build, configuration, account or visibility scope, fixture version, inputs, and the source result reference.
  • Transformation: The exact input or state change, including new IDs, constants, permutations, or generated parameters.
  • Applicability: Domain limits, snapshot assumptions, determinism requirements, and readiness conditions.
  • Observation: Which output fields are collected from each execution and how complete results are obtained.
  • Comparator: The relation to evaluate, including order, multiplicity, units, precision, and any justified tolerance.
  • Additional checks: Known anchors, expected membership, valid counts, or other assertions that address relevant blind spots.
  • Result and evidence: Whether the relation held, the observed discrepancy, missing prerequisites, and links to both executions.

The comparator should identify exactly what it evaluates. "Responses look consistent" cannot distinguish a sequence comparison from a set comparison or explain whether a changing timestamp affected the verdict.

When a source test supports several follow-ups, give each relation evaluation a traceable identity. Reuse of source data does not mean that all generated comparisons have the same prerequisites or result.

For endpoint-level execution details, combine this design with the API test cases checklist. The method described here adds relationships between executions to the individual request and response assertions.

Diagnose a violated relation

Suppose the source execution of case 3 returns the correct four-element result, but sorting the doubled list returns only one occurrence of each value. A useful diagnostic record retains the contradiction explicitly:

  • Source evidence: Input [7, 2, 2, 5] produced [2, 2, 5, 7].
  • Follow-up evidence: Input [7, 2, 2, 5, 7, 2, 2, 5] produced [2, 5, 7].
  • Relation violation: Each source occurrence count should double. For value 2, the expected follow-up count is 4; the observed count is 1.
  • Independent violation: The follow-up input contains eight values, but the output contains only three. This contradicts the declared occurrence-preservation rule directly.
  • Reproduction context: Retain the actual build, configuration, input pair, and comparator version used by the execution.

The independent observation identifies the follow-up output as incorrect, even without knowing the internal cause. Investigating why longer input takes a different path can follow from that evidence; it is not a conclusion established by the relation alone.

In a filtering investigation, a missing readiness checkpoint for D1 leaves a different kind of uncertainty. If the added record never reached the queryable snapshot, the claimed follow-up fixture was not established. Restore or verify the setup before presenting that execution as evidence about the transformed dataset.

Some discrepancies become defects in the test harness. A comparator that converts every list to a set silently discards multiplicity. Correct its comparison unit and review previous results that relied on the same conversion; a green historical run may not have checked the property it claimed to check.

Choose relations and report their limits

Select relations that target meaningful behavior and differ in the defects they can expose. In the sorting model, preserving multiplicity adds evidence that permutation equality alone lacks. In the aggregation model, the first-value counterexample shows a blind spot shared by three otherwise valid relations.

Review sources, transformations, and output comparisons together. Ten relations applied only to identical-valued input may offer less useful evidence about aggregation than a smaller selection with varied data and an independently checked anchor.

Report the relations evaluated, source fixtures, transformation parameters, assumptions reached, and unresolved discrepancies. A count of completed relation checks describes those checks. It does not establish complete input coverage or a percentage of all possible defects detected.

Where relevant, combine relations with boundary, partition, or configuration coverage goals defined elsewhere in the test plan. A transformation must still respect its own prerequisites even when its source was selected through another technique.

Retain stable, valuable comparisons in the regression testing checklist or automated suite for the affected feature. Review them when filtering policy, tie-breaking, deduplication, numeric precision, or fixture assumptions change. A once-valid relation can become an incorrect expectation after a legitimate behavior change.

FAQ

Yes. A known source result can anchor a family of follow-up tests whose expectations are derived through relations. It can also reveal a wrong source execution that would otherwise agree with its follow-ups. Keep the original independently derived expectation instead of replacing it with whatever the program currently returns.

Yes, when they can establish the related inputs and inspect the required outputs. A manual API or UI investigation can execute these steps with saved fixtures and a comparison record. If the interface reveals only a partial page or rounded summary, first determine whether that observation is sufficient for the proposed relation. Automation becomes useful for larger datasets and repeated transformations.

Yes, when their combined prerequisites hold. For the sorting fixture, permuting the input and then adding 10 should produce the source sorted sequence shifted by 10. Preserve the intermediate transformed data so a failure can be investigated one transformation at a time. Composition creates another evaluation; it does not replace the separate checks that help identify which condition failed.

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