Inferensys

Prompt

Mutation Testing Gap Analysis Prompt Template

A practical prompt playbook for using Mutation Testing Gap Analysis Prompt Template in production AI workflows to identify systematic assertion gaps from mutation testing results.
Elegant overhead shot of a polished wooden communal table in a sun-drenched WeWork lounge, laptops and tablets displaying AI workflow dashboards, plants and pendant lights in background.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for mutation testing gap analysis.

This prompt is designed for QA engineers and test infrastructure leads who need to move beyond simple code coverage metrics and understand the quality of their test suite's assertions. The job-to-be-done is systematic weakness discovery: you have a set of mutation testing results showing which code mutations survived your test suite, and you need to categorize these survivors to identify patterns of ineffective assertions. This is not a prompt for generating new tests from scratch or for analyzing a single test failure. It is specifically for the analytical step that sits between running a mutation testing tool (like PIT, Stryker, or MutPy) and planning targeted test improvements.

The ideal user has already run mutation testing on a codebase and has a structured report of killed vs. survived mutations. The required context includes the source code diff for each surviving mutation, the test that was expected to kill it, and any failure or success output. Without this granular, per-mutation evidence, the prompt cannot produce a reliable gap analysis. The prompt works best when the mutation results are grouped by mutation operator type—such as conditionals boundary changes, arithmetic operator replacements, or return value modifications—because the analysis pattern relies on detecting systematic assertion weaknesses within each category. Do not use this prompt when you only have aggregate mutation scores without per-mutant detail, or when the goal is to explain a single flaky test rather than audit the test suite's overall assertion strength.

This prompt is a diagnostic tool, not a code generation engine. It produces a structured gap report that identifies categories of weakness, not a list of specific code fixes. The output should inform a human-led or agent-assisted test improvement sprint. Before using this prompt, ensure your mutation testing tool is configured to output per-mutant details in a parseable format. After receiving the gap analysis, the next step is to prioritize the identified weakness categories by risk impact and feed the highest-priority findings into a test generation workflow. Avoid using this prompt on mutation results that have not been deduplicated or on codebases where the test suite is known to be fundamentally broken—the analysis assumes a baseline of functional tests where assertion gaps are the primary concern, not missing test coverage entirely.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works for mutation testing analysis and where it does not. Use these cards to decide if the gap analysis template fits your current test infrastructure and quality goals.

01

Good Fit: Structured Mutation Reports

Use when: you have mutation testing tool output (PIT, Stryker, Mull) with kill/survive status per mutant. The prompt excels at categorizing surviving mutants by type and mapping them to assertion weaknesses. Guardrail: validate that the input includes mutant type, location, and survival reason before running the analysis.

02

Good Fit: Systematic Assertion Gaps

Use when: your team suspects the test suite has weak or missing assertions across entire categories of mutations. The prompt identifies patterns like missing boundary checks, unverified side effects, or over-broad mocks. Guardrail: pair the output with a manual review of at least one example per mutation category to confirm the pattern is real.

03

Bad Fit: Raw Mutation Logs Without Structure

Avoid when: you only have unstructured CI logs or raw mutation tool output without parsed mutant-level data. The prompt requires categorized mutation types and survival status to produce meaningful gap analysis. Guardrail: preprocess mutation results into structured records with mutant type, location, status, and survival reason before invoking the prompt.

04

Bad Fit: Single Mutant Debugging

Avoid when: you need to understand why one specific mutant survived. This prompt is designed for category-level pattern analysis across many mutants, not individual mutant investigation. Guardrail: use a targeted root cause analysis prompt for single-mutant debugging and reserve this template for aggregate gap reports.

05

Required Inputs

Must provide: mutation testing results with mutant type, source location, survival status, and survival reason. Strongly recommended: test suite size, mutation operator descriptions, and coverage baseline. Guardrail: if survival reasons are missing, the prompt will infer patterns from mutant types alone, but confidence drops significantly—flag the output accordingly.

06

Operational Risk: False Pattern Detection

What to watch: the prompt may identify a mutation category as a systematic gap when only a few unrepresentative mutants survived. Small sample sizes within a category produce unreliable patterns. Guardrail: require a minimum threshold of surviving mutants per category before reporting it as a systematic gap, and include count evidence in the output.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for analyzing mutation testing results and generating a structured gap report.

The following prompt template is designed to be copied directly into your AI harness, IDE, or testing pipeline. It accepts raw mutation testing output and relevant test suite context, then produces a structured gap report organized by mutation type. Every placeholder is enclosed in square brackets and must be replaced with real data before execution. The prompt is self-contained: it includes role assignment, output schema instructions, and explicit constraints that prevent the model from hallucinating fixes or making unsupported claims about test quality.

code
You are a senior QA engineer specializing in mutation testing and test suite effectiveness. Your task is to analyze the provided mutation testing results and test suite context to produce a structured gap report. The report must identify categories of mutations that survived the test suite, explain why they survived, and recommend concrete test improvement strategies.

## INPUT

### Mutation Testing Results
[MUTATION_RESULTS]

### Test Suite Context
- Test framework: [TEST_FRAMEWORK]
- Language: [LANGUAGE]
- Total tests: [TOTAL_TEST_COUNT]
- Test execution time: [EXECUTION_TIME]
- Coverage baseline (line/branch): [COVERAGE_BASELINE]
- Mutation operators applied: [MUTATION_OPERATORS_LIST]

### Repository Context (Optional)
[REPOSITORY_CONTEXT]

## OUTPUT SCHEMA

Return a JSON object with the following structure:

{
  "summary": {
    "total_mutations": <number>,
    "killed": <number>,
    "survived": <number>,
    "timeout": <number>,
    "mutation_score_percent": <number>,
    "analysis_timestamp": "<ISO 8601>"
  },
  "gap_categories": [
    {
      "mutation_type": "<string, e.g., CONDITIONALS_BOUNDARY, RETURN_VALUES, MATH, NEGATE_CONDITIONALS, VOID_METHOD_CALLS, INCREMENTS, INVERT_NEGS>",
      "survived_count": <number>,
      "severity": "<CRITICAL | HIGH | MEDIUM | LOW>",
      "description": "<explanation of why this mutation type survived and what testing weakness it reveals>",
      "affected_modules": ["<module path or class name>"],
      "root_cause": "<systematic reason: missing assertions, weak oracles, untested paths, mock overuse, etc.>",
      "improvement_strategies": [
        {
          "strategy": "<concrete action, e.g., Add boundary assertion for return value>",
          "effort": "<LOW | MEDIUM | HIGH>",
          "expected_impact": "<description of how many mutations this would kill>"
        }
      ]
    }
  ],
  "top_improvement_actions": [
    {
      "rank": <number>,
      "action": "<description>",
      "target_mutation_types": ["<string>"],
      "estimated_kill_increase": <number>,
      "effort": "<LOW | MEDIUM | HIGH>"
    }
  ],
  "limitations": [
    "<caveat about analysis, e.g., equivalent mutants not distinguished, timeout mutations may indicate performance issues rather than assertion gaps>"
  ]
}

## CONSTRAINTS

1. Only analyze mutations present in the provided results. Do not invent or assume mutations.
2. Group surviving mutations by mutation operator type. If fewer than 3 mutations of a type survived, merge them into an "OTHER" category with a note.
3. For each gap category, cite at least one specific example from [MUTATION_RESULTS] as evidence.
4. Severity assignment: CRITICAL if the mutation type reveals missing safety or security assertions; HIGH if core business logic is unverified; MEDIUM if error handling or edge cases are untested; LOW if cosmetic or unlikely to affect behavior.
5. Do not recommend deleting tests or lowering coverage targets.
6. If [REPOSITORY_CONTEXT] is provided, reference specific files or functions when suggesting improvements. If not provided, keep suggestions generic but actionable.
7. Mark any finding where you have low confidence with "confidence: LOW" and explain why.
8. Do not fabricate mutation scores, test names, or file paths not present in the input.

## EXAMPLES

### Example Input (Abbreviated)
Mutation: org.example.Calculator.add(int,int) - Replaced integer addition with subtraction - SURVIVED
Mutation: org.example.Calculator.divide(int,int) - Replaced double return with 0.0 - SURVIVED

### Example Output Fragment
{
  "gap_categories": [
    {
      "mutation_type": "MATH",
      "survived_count": 1,
      "severity": "HIGH",
      "description": "Arithmetic mutation in Calculator.add survived because the test only asserts non-null return, not the correct sum.",
      "affected_modules": ["org.example.Calculator"],
      "root_cause": "Weak assertion: test checks result is not null but does not verify the computed value.",
      "improvement_strategies": [
        {
          "strategy": "Add assertion verifying add(2,3) returns 5 exactly.",
          "effort": "LOW",
          "expected_impact": "Would kill all MATH mutations in Calculator.add"
        }
      ]
    }
  ]
}

## INSTRUCTIONS

1. Parse [MUTATION_RESULTS] to extract all surviving mutations.
2. Group by mutation operator.
3. For each group, determine the root cause of survival by comparing the mutation to what the existing tests actually assert.
4. Generate the output JSON following the schema exactly.
5. If the input is malformed or missing critical fields, return a JSON object with an "error" key describing what is missing.

To adapt this template, replace [MUTATION_RESULTS] with the raw output from your mutation testing tool—PIT, Stryker, Mull, or similar—in its native format. The prompt works best with detailed mutation descriptions that include the mutated source location, the operator applied, and the survival status. If your tool produces only summary statistics, add a preprocessing step that expands summaries into per-mutation records before passing them to the model. The [REPOSITORY_CONTEXT] placeholder is optional but strongly recommended: include relevant source files, test files, and any existing coverage reports to ground the analysis in real code. For high-risk codebases such as financial calculations, authentication logic, or safety-critical systems, always route the output through human review before acting on improvement recommendations. Validate the JSON output against the schema before ingestion into your test planning workflow, and log any schema violations for prompt refinement.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the mutation testing gap analysis prompt. Each placeholder must be populated with concrete data before the prompt is sent. Validation notes describe how to verify the input is well-formed and safe to use.

PlaceholderPurposeExampleValidation Notes

[MUTATION_REPORT]

Raw mutation testing output from a tool such as PIT, Stryker, or MutPy

pasted XML/JSON/HTML report or path to parsed results file

Parse check: must contain at least one mutation or mutant node with status='SURVIVED'. Reject empty reports or reports with zero survived mutations.

[SOURCE_MODULE]

The target module, class, or file path under analysis

src/main/java/com/example/PricingEngine.java

Must resolve to a real file path or fully qualified class name in the repository. Null not allowed. Validate against repository file tree before prompt assembly.

[TEST_SUITE]

The test suite or test class associated with the source module

src/test/java/com/example/PricingEngineTest.java

Must resolve to a real test file path. If the test suite spans multiple files, list all paths. Validate existence in the repository. Null allowed only if no dedicated test file exists, but flag as high-risk.

[MUTATION_OPERATORS]

List of mutation operators enabled during the run

CONDITIONALS_BOUNDARY, INCREMENTS, MATH, NEGATE_CONDITIONALS, RETURN_VALS, VOID_METHOD_CALLS

Must be a non-empty list of known operator names from the mutation tool's vocabulary. Validate against the tool's operator catalog. Reject unknown operator names to prevent hallucinated gap analysis.

[SURVIVED_THRESHOLD]

Minimum number of survived mutations required to trigger a full gap report

5

Integer >= 1. If fewer mutations survived, the prompt should return a summary-only response rather than a full gap analysis. Validate as positive integer before prompt assembly.

[OUTPUT_SCHEMA]

Expected JSON schema for the gap report output

See output-contract table for field definitions

Must be a valid JSON Schema object. Validate with a schema validator before passing to the prompt. Reject schemas that lack required fields: mutation_type, survivor_count, root_cause, test_improvement_strategy.

[CONTEXT_LIMIT]

Maximum token budget for the mutation report context window

8000

Integer >= 2000. If the mutation report exceeds this limit, truncate or summarize before prompt assembly. Validate against the model's context window minus prompt overhead. Log a warning if truncation occurs.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the mutation testing gap analysis prompt into a CI pipeline or test analysis workflow.

Integrating this prompt into a CI pipeline requires treating it as a post-mutation-testing analysis step, not a standalone script. The prompt expects structured mutation testing results—typically the output of tools like PIT, Stryker, or Mull—as its primary input. Before calling the LLM, your harness must parse raw mutation reports into the [MUTATION_REPORT] placeholder format, extracting fields like mutation operator, mutated class, line number, and kill status. This normalization step is critical because raw tool outputs vary in schema, and the prompt's reasoning quality depends on consistent input structure. The harness should also inject [CODEBASE_CONTEXT] by pulling relevant source files for surviving mutations, ensuring the model can reason about why a specific mutation evaded detection.

For production use, implement a validation layer that checks the LLM's output against a defined [OUTPUT_SCHEMA] before surfacing results. The schema should enforce that each gap category includes a mutation type, survival count, root cause hypothesis, and test improvement strategy. Use a JSON Schema validator in your pipeline to catch malformed responses and trigger a retry with the error message appended to the prompt. Set a maximum of two retries before falling back to a partial report with a warning flag. Log every LLM call with the input report hash, model version, response latency, and validation status for auditability. For high-risk codebases—safety-critical systems, financial logic, or security-sensitive modules—route the gap analysis through a human review queue before accepting test improvement recommendations. The harness should also compare gap categories across runs to detect regressions in test suite quality over time.

Model choice matters here: use a model with strong code reasoning capabilities and a large context window, as mutation reports for substantial codebases can be verbose. If the report exceeds the context limit, implement a chunking strategy that groups mutations by package or class and runs the prompt in parallel, then merge results with a deduplication step. Avoid running this analysis on every commit; instead, trigger it on a schedule (e.g., weekly) or after significant test suite changes. The harness should store historical gap reports to track whether identified gaps are being closed, creating a feedback loop that measures the prompt's real-world impact on test quality. Never treat the LLM's output as ground truth—always verify suggested test improvements by actually writing and running the tests against the surviving mutations.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the mutation testing gap analysis report. Use this contract to parse, validate, and store the model output before surfacing it in a dashboard or review queue.

Field or ElementType or FormatRequiredValidation Rule

report_title

string

Must be non-empty and contain the phrase 'Mutation Testing Gap Analysis'

generated_at

ISO 8601 datetime string

Must parse as valid ISO 8601; reject if in the future beyond a 5-minute clock skew tolerance

mutation_framework

string

Must match one of the allowed enum values: 'stryker', 'pitest', 'mutpy', 'mutmut', 'custom'

total_mutations

integer

Must be a positive integer; must equal the sum of killed_mutations + survived_mutations + timeout_mutations if provided

survived_mutations

integer

Must be a non-negative integer; must be less than or equal to total_mutations

gap_categories

array of objects

Each object must contain 'mutation_type' (string, non-empty), 'survivor_count' (integer, >=0), 'root_cause' (string, non-empty), and 'improvement_strategies' (array of strings, min 1 item)

overall_assessment

object

Must contain 'severity' (enum: 'critical', 'high', 'medium', 'low'), 'summary' (string, 50-500 characters), and 'recommended_priority_order' (array of strings matching gap_categories[*].mutation_type)

evidence_references

array of strings

If present, each entry must be a non-empty string referencing a specific mutation ID, file path, or test name from the input context

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when analyzing mutation testing results and how to guard against it.

01

Survivor Misclassification

What to watch: The model conflates 'survived' mutants with 'killed' mutants, producing a gap report that misses real assertion weaknesses. This often happens when mutation tool output is verbose or poorly structured. Guardrail: Pre-process mutation logs into a strict JSON schema with explicit status: killed | survived | timeout | runtime_error fields before the prompt. Validate that every cited survivor in the report matches the input data.

02

Vague Improvement Suggestions

What to watch: The model generates generic advice like 'add more assertions' or 'improve test coverage' without specifying which assertions are missing or what edge cases to target. Guardrail: Require the output schema to include a missing_assertion_type field (e.g., boundary_check, side_effect_verification, exception_validation) and a suggested_test_case stub for each gap. Reject outputs that lack concrete, testable suggestions.

03

Equivalent Mutant Confusion

What to watch: The model treats equivalent mutants (code changes that don't alter observable behavior) as real gaps, recommending tests for behavior that cannot be distinguished. This wastes engineering time on impossible tests. Guardrail: Include an equivalent_mutant_indicators field in the input context (e.g., operator type, location in dead code, compiler-optimized paths). Instruct the model to flag suspected equivalent mutants and skip test recommendations for them.

04

Operator Blindness

What to watch: The model focuses only on one mutation operator type (e.g., arithmetic) and ignores survivors from other operators (e.g., conditional boundary, return value, method call), producing a skewed gap analysis. Guardrail: Group input data by mutation_operator and require the output to include a coverage_by_operator summary. If any operator with survivors is missing from the analysis, flag the output as incomplete.

05

Context Window Truncation

What to watch: Large mutation reports exceed the model's context window, causing silent truncation of survivor data. The model then analyzes only a partial dataset, missing critical gaps in untruncated sections. Guardrail: Chunk mutation results by module or operator before prompting. Run analysis per chunk, then merge results with a deduplication pass. Log input token counts and verify that all survivor IDs from the source appear in the output.

06

Source-Code Hallucination

What to watch: The model invents code snippets, line numbers, or function signatures that don't exist in the actual codebase when explaining why a mutant survived. This creates plausible-looking but incorrect remediation guidance. Guardrail: Require every code reference in the output to include a source_file and line_number that can be validated against the provided source context. Add an eval step that greps the source for cited identifiers and rejects unmatched references.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality and safety of a mutation gap analysis report before it is shipped to a QA engineer or merged into a test improvement backlog.

CriterionPass StandardFailure SignalTest Method

Mutation Category Coverage

Every surviving mutation ID from [MUTATION_REPORT] is assigned to exactly one gap category

Orphaned mutation IDs appear in the output without a category label

Parse output JSON, extract all mutation IDs, and diff against the input mutation ID set

Gap Root Cause Specificity

Each gap category includes a root cause statement that references a specific assertion weakness (e.g., missing null check, over-broad regex)

Root cause field contains vague language like 'assertion issue' or 'test needs improvement'

LLM-as-judge check: prompt a second model to classify root cause statements as specific or generic; require >80% specific

Improvement Strategy Actionability

Every gap category includes at least one concrete test improvement strategy with a code-level suggestion pattern

Improvement strategy is a restatement of the gap without a suggested fix pattern or example assertion shape

Regex match for code-like patterns (e.g., assertThrows, expect().to, should) in improvement strategy text

False Positive Flagging

Report explicitly flags mutation categories likely to be equivalent mutants or low-value findings

Report treats all surviving mutations as equally actionable without distinguishing noise from signal

Keyword search for 'equivalent', 'low-priority', 'acceptable', or 'by-design' in the output; require at least one flag if >10 surviving mutations

Source Grounding

Every gap category references at least one specific mutation ID or source location from [MUTATION_REPORT]

Gap category describes a general testing weakness without linking to any concrete mutation evidence

Validate that each gap category object contains a non-empty 'source_mutation_ids' or 'source_locations' field

Severity Ranking Consistency

Gap categories are ordered by severity, and the severity rationale references mutation count, affected code paths, or risk surface

Severity ordering appears random or all categories share the same severity level without justification

Check that severity field values are monotonically non-increasing in the output array; flag if all severities are identical

Output Schema Compliance

Output strictly matches [OUTPUT_SCHEMA] with all required fields present and no extra top-level keys

Output is valid JSON but missing required fields or includes undocumented fields

JSON Schema validation against [OUTPUT_SCHEMA]; reject on validation errors

Confidence Calibration

Report includes a confidence indicator per gap category, and low-confidence findings include explicit caveats

Report presents all findings with equal certainty or omits confidence indicators entirely

Assert that a 'confidence' field exists per category with values in [high, medium, low]; flag if all are 'high'

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single mutation testing framework and a smaller mutation operator set. Remove the structured JSON output requirement initially—ask for a markdown report to iterate faster on the analysis quality.

Simplify the prompt template:

  • Replace [MUTATION_TESTING_TOOL_OUTPUT] with raw console output from a single run of stryker or pitest.
  • Set [MUTATION_OPERATORS_OF_INTEREST] to a short list like [CONDITIONALS_BOUNDARY, RETURN_VALUES].
  • Remove [OUTPUT_SCHEMA] and ask for a free-text gap report organized by mutation type.

Watch for

  • The model hallucinating mutation operator names not present in your tool output
  • Overly generic advice like "add more tests" without specific assertion patterns
  • Missing distinction between equivalent mutants and genuinely survivable mutations
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.