~/qa-guides

~/qa-guides/mutation-testing

>_ Mutation Testing: Surviving and Equivalent Mutants

Investigate surviving and equivalent mutants with three models and six worked cases. Includes test inputs, assertion improvements, a finite equivalence proof, and mutation score calculations.

Mutation testingTest designTest assertionsTest coverage

Published

Short answer

Mutation testing evaluates tests by running them against deliberately changed versions of a program. Each changed version is a mutant. A mutant is killed when a test fails with it active; a surviving mutant completes the selected tests without a failure.

A survivor needs investigation. The tests may miss the changed behavior, the selected inputs may not distinguish it, or the change may be equivalent to the original over the defined input domain and observable behavior. Passing a few examples does not establish equivalence.

This guide uses three fictional models: a review threshold, an active-record filter, and a quantity cap. The mutations and results are constructed teaching examples, not output from a mutation run on a real application. The focus is investigating results and improving tests, rather than installing a particular runner.

What mutation testing asks about your tests

Statement and branch coverage describe which structural elements the tests exercise. Mutation testing asks whether the selected tests detect particular changes to the implementation. Reaching a condition and checking its meaningful consequences are different observations.

For example, tests below and above a threshold can exercise both decision outcomes while missing an incorrect equality operator. A filter can execute every predicate evaluation while a length-only assertion overlooks the wrong returned records.

Differential testing compares comparable implementations under an explicit contract. Mutation testing deliberately introduces implementation changes to investigate test sensitivity. The original program still needs independently justified expectations; a green baseline does not establish that every business rule is correct.

A mutation result describes a specific population of changes, selected code, and selected tests. It does not measure every possible defect. Use it when strengthening a test suite around changed logic, investigating a suspiciously weak assertion, or assessing tests before a refactor.

Prepare a trustworthy mutation experiment

1. Establish a passing, repeatable baseline

Run the selected tests against the unchanged implementation first. Record the code revision, test selection, fixture version, and relevant configuration.

Resolve a baseline failure before attributing that same failure to a mutant. If a test depends on a changing clock, shared mutable records, or an unavailable service, stabilize or isolate those dependencies sufficiently to interpret the experiment.

A known failure on both the original and changed program is not evidence that the change was detected. Retain the failure details, rather than treating any red test as a successful mutation result.

2. Define the input domain and observations

Specify valid input types, ranges, and units. Decide whether the relevant observation is a return value, selected record, rejection, stored state, event, or a combination of these.

Equivalence depends on this scope. A pure integer calculation permits a different argument from an operation that also changes records or emits events. An input outside the declared domain cannot establish a valid behavioral counterexample without first resolving what the contract requires there.

Use test data design to make the fixture and independent expectation reproducible. Include enough distinguishing data to reveal the targeted change; an empty collection may execute a wrapper without evaluating its filtering rule.

3. Activate one change at a time

Keep the original implementation as the baseline and identify the exact changed expression for each mutant. Run different mutants independently.

Combining two changes can hide their individual effects. One altered condition might compensate for an altered calculation, making the combined result agree for reasons unrelated to either mutation's individual behavior.

The examples below use hand-specified changes. They demonstrate reasoning about mutants; they do not claim that every runner generates those exact edits or uses the same mutation operators.

4. Verify the selected tests execute the intended implementation

Check test discovery, selection, imports, and replaced dependencies. A test can have the expected name and pass while invoking a stub instead of the changed function.

Record which tests ran and what execution evidence is available for the mutation location. Distinguish the application's source revision from a generated or cached artifact that the runner might actually load.

If the configured run excludes the relevant tests, correct that experiment before using the result to judge the broader suite. The outcome belongs to the tests that actually ran.

5. Attribute a failure before treating it as detection

Inspect the failing expectation and confirm it passes on the unchanged program. A useful killing test checks a behavior the contract requires and the mutant violates.

Keep assertion failures separate from runner errors and timeout outcomes in the investigation. Those outcomes can receive different treatment in a tool's score, as the report example later shows.

Retain the mutation identifier and smallest useful reproduction. This lets a reviewer verify the connection between the code change, effective input, and failed observation.

Worked example 1: a survivor at a review threshold

Declare the R1 contract and mutation

The function receives one already validated integer score from 0 through 100 inclusive. Its only behavior is a two-outcome decision: return Review when score >= 60, otherwise return Clear. It has no persistence or other effects.

Mutant M1 changes the condition to score > 60. Existing tests check that score 50 returns Clear and score 70 returns Review.

ScoreOriginalM1
50ClearClear
70ReviewReview
60ReviewClear

The first two tests exercise both outcomes of the original decision. They also pass under M1 because neither input exercises the changed equality behavior. The mutation result identifies a selection gap that an outcome-coverage count alone does not expose.

Test case 1: add the missing equality observation

  • Setup: Use the R1 contract, the original implementation, and independent tests for scores 50 and 70. Both tests must pass before activating M1.
  • Action: Run those tests with M1 active and record their agreement. Then add a test asserting that score 60 returns Review.
  • Expected result: The expanded suite passes on the original program. With only M1 active, the new test fails because it receives Clear instead of Review.
  • Evidence: Retain the exact input, expected decision, observed decision, and mutation location. The failure is attributable to the changed threshold operator.

The new expectation comes from the rule that includes 60. Copying M1's observed Clear result into the test would preserve the gap and encode an incorrect requirement.

Boundary value analysis provides a systematic reason to select the equality input before mutation analysis finds the omission. The mutation adds evidence that the existing selection failed to distinguish this particular implementation error.

After strengthening the test, rerun the relevant mutation scope. One killed mutant establishes detection of its change; other operators or locations may require different inputs or observations.

Worked example 2: a changed filter with the same result count

Define the F0 fixture and selection rule

The function receives the complete ordered list below. Each record has an ID and a state. For this model, the only states are Active and Archived. There is no pagination, additional filtering, or concurrent modification.

IDStatePosition
J01Active1
J02Archived2
J03Active3
J04Archived4

The function returns all Active records unchanged, preserving their input order. The independently expected IDs are [J01, J03].

Mutant M2 changes the predicate from state === "Active" to state !== "Active". In F0, its result is [J02, J04]. Both results contain two records, but they represent different business data.

Test case 2: strengthen a length-only assertion

  • Setup: Call the real filter with F0. The original test asserts only that the returned array has length 2.
  • Action: Run that test on the original and M2 separately. Then strengthen it to compare the exact ordered ID sequence with [J01, J03].
  • Expected result: The length-only test passes on both implementations. The strengthened test passes on the original and fails on M2 because its IDs are [J02, J04].
  • Evidence: Preserve both result sequences, rather than recording only the common count.

This is an assertion gap, not a lack of predicate execution. All four records reach the filter in both runs, and the changed predicate produces a different result that the original assertion does not examine.

The ID check has a defined purpose: establish which records were selected and in what order. It does not automatically check every field's unchanged value. Add observations for other promised behavior when the targeted mutation or contract makes them relevant.

Test case 3: change data to distinguish the existing property

Create fixture F1 by changing only J03's state from Active to Archived. Preserve the same four IDs and their order. F1 now has one Active record and three Archived records.

  • Setup: Use F1 and its independent expectation of one result, J01. Keep this fixture separate from F0.
  • Action: Run a length assertion of 1 on the original and M2 independently.
  • Expected result: The original returns [J01] and passes. M2 returns [J02, J03, J04], giving length 3 and failing the assertion.
  • Evidence: Record the fixture version and changed state alongside the result. An expectation of 2 belongs to F0 and would be incorrect for F1.

Here, new data makes the selected count property discriminate between the implementations. That does not make the original F0 assertion complete: it still ignores identity on a balanced fixture.

Choose the improvement based on the requirement. For a filter whose purpose is selecting specific records, checking their identities directly is useful even when another dataset lets a count assertion kill the same mutant.

Test case 4: detect a mock that bypasses the changed code

Suppose a test imports the filter through a dependency that has been replaced with a stub. The stub always returns the fixed records J01 and J03. The real filter implementation is never called.

  • Setup: Use F0, the fixed stub, and the exact-ID expectation [J01, J03] from test case 2.
  • Action: Run the test and inspect whether execution enters the actual mutation location. Then repeat with the real filter restored and only surrounding dependencies isolated.
  • Expected result: The stubbed test passes regardless of M2 because it never executes the changed predicate. The real-filter test passes on the original and fails on M2.
  • Evidence: Retain the effective dependency binding and execution information, not just the passing assertion result.

With suitable coverage information, a runner can identify the unexecuted mutation location as No coverage. Inspect the actual report; the key observation in this case is that the test bypasses the intended implementation.

Replacing a database or remote service around the target can be appropriate. Replacing the target itself changes what the test establishes. An exact assertion against a fixed stub response cannot assess the source code that response bypasses.

Worked example 3: prove an equivalent quantity-cap mutant

Define the pure C1 calculation

The function receives an already validated integer q from 0 through 20 inclusive. Return 10 if q > 10; otherwise return q. Its entire observable behavior is that returned integer. There are no events, logs, mutations of arguments, or hidden state.

Mutant M3 changes only the condition to q >= 10. The two conditions choose different branches at q equal to 10, but both branches return 10 there.

The Stryker discussion of equivalent mutants describes changes that cannot be distinguished from the original behavior. The C1 argument below uses its own complete finite domain and explicitly declared observations.

Input setOriginal pathM3 pathReturned value
0 through 9Return qReturn qq
10Return qReturn 1010
11 through 20Return 10Return 1010

The rows partition all 21 permitted inputs: ten below 10, one equal to 10, and ten above it. Every input falls into one row, and each row establishes the same returned value for the two implementations.

Test case 5: exhaust the finite domain and retain the argument

  • Setup: Use C1 exactly as specified, including its integer domain and absence of other effects. Test the original and M3 independently.
  • Action: Evaluate every integer from 0 through 20 on each implementation. Compare each returned value with the independently specified capped value.
  • Expected result: Both implementations return q for inputs 0 through 10 and return 10 for inputs 11 through 20. No permitted input distinguishes them under C1's observation.
  • Evidence: Retain the 21 input-result comparisons and the three-part argument above as the equivalence rationale.

The justification is stronger than trying a few convenient examples and finding no failure. It covers the entire stated finite domain and explains why the different branch at equality has no observable consequence.

This does not establish a general method for proving every survivor equivalent. Larger domains, shared state, exceptions, and additional effects require their own reasoning. If the available evidence does not resolve the question, record it as unresolved rather than assigning an equivalence label for convenience.

Test case 6: include a required flag before judging equivalence

Now consider a separate contract, C2. It accepts the same inputs but returns both the capped quantity and a Boolean flag named capped. That flag is true exactly when the requested quantity exceeded 10.

The original conditional returns quantity 10 with capped true on its q > 10 path, and quantity q with capped false otherwise. Mutant M4 changes that condition to q >= 10 while leaving both returned objects as they were.

  • Setup: Use C2, where both quantity and capped are required observations. This is a different function contract from pure C1.
  • Action: Submit q equal to 10 to the original and M4 independently. Check both returned fields.
  • Expected result: The original returns quantity 10 and capped false. M4 returns quantity 10 and capped true, so a correct flag assertion fails under M4.
  • Evidence: Retain the complete output. Comparing only quantity would discard the distinguishing required behavior.

C1's proof does not transfer to C2 because the observation changed. Conversely, a flag introduced solely to distinguish C1's branches would not be evidence of a requirement that C1 already had. Evaluate equivalence against the actual contract and effects of the target operation.

Choose an action for a surviving mutant

Keep the next step tied to the finding:

  • The target was bypassed: Correct the test binding, selection, or execution setup and reassess the mutant.
  • The data did not distinguish the change: Add a justified boundary or fixture variant with an independently calculated expectation.
  • The result changed but the assertion missed it: Check the relevant identity, value, state, or effect that the contract promises.
  • Equivalence is established for the declared scope: Preserve the rationale and review it when that scope changes.
  • The finding is unresolved: Record the exact missing evidence, owner, and investigation step instead of treating uncertainty as proof.

Do not change a correct business expectation merely to create a failure. Likewise, avoid rewriting correct production behavior solely to improve a percentage. An accepted equivalence finding and an improved assertion solve different problems.

Calculate mutation scores with an explicit denominator

The following status names and formulas follow Stryker's mutant states and metrics. Other reports may use different conventions; record the definition used for the calculation.

This fictional snapshot contains 24 mutants, including one still awaiting execution:

StatusCountObservationScore treatment
Killed12Test failedDetected
Timeout2Time limit exceededDetected
Survived4Tests passedUndetected
No coverage2Changed code untestedUndetected
Compile error1Compilation failedExcluded
Runtime error1Execution erroredExcluded
Ignored1Excluded from testingExcluded
Pending1Awaiting executionExcluded

Use the runner's assigned status. An unexpected exception that fails a test may produce Killed; Runtime error here means the report's execution-error category. The word "error" in a log is insufficient to choose between them.

Under these definitions, detected is killed plus timeout; valid is detected plus survived plus no coverage; covered is detected plus survived. Mutation score divides detected by valid, while the covered-code score divides detected by covered.

For this snapshot:

  • Detected: 12 + 2 = 14.
  • Undetected: 4 + 2 = 6.
  • Valid: 14 + 6 = 20.
  • Covered: 14 + 4 = 18.
  • All categories: 12 + 2 + 4 + 2 + 1 + 1 + 1 + 1 = 24.
  • Mutation score: 14 / 20 x 100 = 70%.
  • Covered-code mutation score: 14 / 18 x 100, approximately 77.8%.

The two percentages answer different questions. The covered-code calculation omits the two No coverage mutants from its denominator. Reporting only that higher number would hide an execution gap visible in the full score.

Timeouts count as detected in this convention. Keep their count visible: a time-limit outcome does not show that an assertion checked the correct business result. Investigate an unexpectedly slow or unstable experiment before interpreting it as useful detection evidence.

Finish pending work before describing a completed run

The 70% snapshot is not a completed assessment because one mutant remains Pending. Suppose its eventual result is Killed and no other status changes.

Killed becomes 13, Pending becomes 0, detected becomes 15, and valid becomes 21. The total population remains 24. The completed mutation score is 15 / 21 x 100, approximately 71.4%. Covered becomes 19, so the covered-code score is approximately 78.9%.

This score changed because another result arrived, without adding a new assertion. Retain the report state and raw counts when comparing runs.

If two of the four survivors are manually established as equivalent, record those findings alongside the native result. Do not silently recalculate the tool's displayed score or imply that all four survivors are missing tests. Any separately adjusted measure needs its own definition and an explicit list of exclusions.

Compare runs only when their scopes are comparable

Keep the selected files, mutation operators, generated population, test selection, exclusions, and relevant tool configuration with the result. A higher percentage after narrowing the mutation scope does not by itself establish a stronger test suite.

For a small changed module, review the remaining mutants individually. For a larger run, prioritize important behavior and unexplained survivors while keeping excluded or unexecuted areas visible. A single percentage should not erase the investigation record.

Where the denominator is zero, report that the chosen scope supplies no applicable observations for that measure. Do not manufacture a successful percentage from an empty population.

A filled survivor investigation record

This filled record uses the fictional F0 filter and its declared expectation. Adapt the fields to the runner's actual report.

  • Target and revision: The F0 active-record filter at teaching revision Filter-1.
  • Mutation: M2 changes the Active equality predicate to inequality; no other mutation is active.
  • Executed setup: The real filter receives all four F0 records in their declared order, without the fixed-response stub.
  • Baseline: The length-only expectation of 2 passes on the original implementation.
  • Mutant observation: M2 returns [J02, J04]. The same length-only expectation passes, leaving a survivor.
  • Independent expectation: The required ordered IDs are [J01, J03] because those are F0's Active records.
  • Classification: The mutated predicate is exercised and changes the selected records; the existing assertion omits that distinction.
  • Change to tests: Add the exact-ID assertion while preserving the valid original expectation.
  • Verification: The strengthened test passes on the unchanged filter and fails with M2 alone active.
  • Follow-up: Rerun the selected mutation scope and retain the new assertion in the relevant regression suite.

Attach the fixture identity, effective input, raw output, failed assertion, and runner selection where available. If the observed behavior suggests a missing requirement, resolve that requirement before choosing a test expectation.

Use the regression testing checklist to connect the strengthened check to future changes affecting this filter. The useful retained asset is the independently justified behavior check, not a dependency on one generated mutation identifier.

FAQ

No. Duplicate mutants behave like one another; equivalent mutants behave like the original within the declared scope. Those relationships need separate evidence.

For R1's integer domain, M1's score > 60 and another mutant using score >= 61 return the same decisions for every permitted score. They are duplicates of each other, but both differ from the original score >= 60 at score 60. The equality test kills each mutant when run independently.

If a report retains both, they are two entries in its population. Record whether deduplication changes that population before comparing scores across runs.

No. A test at another level can detect a changed observable behavior if it executes the mutated implementation and has an appropriate expectation. For example, an integration test may expose an incorrect saved value that a calculation-only check cannot observe.

Choose the smallest practical scope that exercises the required behavior and gives a dependable failure. Broader tests can add meaningful evidence, but they also introduce more dependencies to investigate. Record which selected suite killed the mutant rather than attributing its detection to every test level.

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