Inferensys

Prompt

Mock and Stub Misconfiguration Diagnosis Prompt Template

A practical prompt playbook for diagnosing mock and stub misconfiguration in production AI workflows. Compares mock configurations, stub behaviors, and expected-versus-actual interaction patterns to identify misconfiguration root causes when tests pass locally but fail in CI or vice versa.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, required context, and limitations for the mock and stub misconfiguration diagnosis prompt.

This prompt is for developers and test infrastructure engineers who are debugging tests that pass in one environment but fail in another—typically passing locally while failing in CI, or vice versa. The core job-to-be-done is comparing mock configurations, stub behaviors, and expected-versus-actual interaction patterns across environments to identify the root cause of the discrepancy. The prompt assumes you have already ruled out genuine application logic bugs, race conditions, and infrastructure failures, and that the most likely culprit is a misconfiguration in how mocks, stubs, or test doubles are set up or behaving differently between environments.

To use this prompt effectively, you must provide concrete evidence from both environments: the test code itself, mock or stub setup files (e.g., jest.mock() calls, sinon.stub() configurations, unittest.mock patches, or WireMock mappings), CI execution logs showing the failure, and local execution output showing the passing case. The prompt works by systematically comparing the mock configurations, expected interaction contracts (expected calls, arguments, return values), and actual interaction patterns (actual calls received, unexpected interactions) across the two environments. It produces a structured discrepancy report with fix suggestions grounded in the provided evidence, not speculation. The prompt is most effective when the mock framework and language are consistent across environments—if you're comparing a Python unittest.mock setup against a Java Mockito configuration, the prompt will need additional translation context.

Do not use this prompt when the failure is caused by genuine timing issues, actual service unavailability in CI, environment variable differences unrelated to mocking, or application code changes that introduced real bugs. This prompt is also not suitable for diagnosing flaky tests that pass and fail intermittently in the same environment—those require a different approach focused on race conditions, test ordering dependencies, or resource contention. Before running this prompt, verify that the test failure is consistently reproducible in one environment and consistently passing in another, and that you have access to the full mock setup code and execution logs from both sides. If you cannot provide evidence from both environments, the prompt will produce low-confidence results that may waste investigation time.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Understand the boundaries before wiring it into your test infrastructure.

01

Good Fit: CI vs Local Discrepancies

Use when: Tests pass locally but fail in CI, or vice versa, and the root cause is suspected to be mock configuration drift. Why it works: The prompt systematically compares mock behaviors, environment variables, and stub return values across execution contexts. Guardrail: Always provide both local and CI mock configuration files, plus the failing test output, to enable accurate discrepancy detection.

02

Good Fit: Interaction Contract Violations

Use when: Tests fail because mocked dependencies receive unexpected arguments, call counts, or call ordering. Why it works: The prompt compares expected-versus-actual interaction patterns and identifies where the test's expectations diverge from the implementation's actual calls. Guardrail: Include the mock framework's verification error output and the interface contract definition for precise mismatch identification.

03

Bad Fit: Non-Deterministic Logic Bugs

Avoid when: The test failure is caused by actual logic errors, race conditions, or algorithmic bugs rather than mock configuration. Why it fails: The prompt is designed for interaction and configuration mismatch diagnosis, not general debugging. Misapplying it will produce false mock-blame reports. Guardrail: First confirm the failure is mock-related by running the test with real dependencies or simplified stubs before using this prompt.

04

Required Inputs: Configuration and Context

Required: Local mock configuration, CI mock configuration, the failing test code, the test failure output, and the interface or contract being mocked. Why it matters: Without both configuration snapshots, the prompt cannot identify discrepancies. Without the contract, it cannot distinguish intentional differences from misconfigurations. Guardrail: Validate that all required inputs are present and non-empty before invoking the prompt; return an actionable error message if inputs are incomplete.

05

Operational Risk: Configuration Drift Over Time

Risk: Mock configurations diverge silently as dependencies evolve, causing the prompt to report expected drift as misconfiguration. Why it matters: The prompt may flag intentional version bumps or API changes as errors, generating noise. Guardrail: Pair this prompt with a mock freshness audit that runs periodically. Flag discrepancies that persist across multiple runs for human review rather than auto-applying fixes.

06

Operational Risk: Over-Reliance on Diff Output

Risk: Teams may treat the prompt's discrepancy report as a complete fix list without understanding the underlying dependency contracts. Why it matters: Blindly applying suggested fixes can introduce new failures if the CI configuration is actually correct and the local configuration is stale. Guardrail: Require human review of all discrepancy reports before applying changes. Add a confidence score to each finding and escalate low-confidence matches for manual investigation.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt template for diagnosing mock and stub misconfigurations that cause test failures.

This section provides a complete, copy-ready prompt template for diagnosing mock and stub misconfiguration issues in your test suite. The template is designed to be pasted directly into your AI coding agent or LLM interface. It guides the model through a structured comparison of mock configurations, stub behaviors, and expected-versus-actual interaction patterns to identify the root cause of discrepancies—particularly the common scenario where tests pass locally but fail in CI, or vice versa. Replace every square-bracket placeholder with your actual test code, failure logs, mock setup files, and environment configuration before running the prompt.

markdown
## Role
You are a senior test infrastructure engineer specializing in mock and stub behavior analysis. Your task is to diagnose why a test that uses mocks or stubs is failing, with particular attention to discrepancies between local and CI execution environments.

## Inputs
- **Failing Test Code:** [PASTE_FAILING_TEST_CODE_HERE]
- **Mock/Stub Configuration:** [PASTE_MOCK_SETUP_CODE_HERE]
- **Test Failure Output:** [PASTE_FULL_FAILURE_LOG_OR_STACK_TRACE_HERE]
- **Local Environment Details:** [DESCRIBE_LOCAL_ENV_OS_DEPS_VERSIONS]
- **CI Environment Details:** [DESCRIBE_CI_ENV_OS_DEPS_VERSIONS]
- **Expected Behavior Description:** [DESCRIBE_WHAT_THE_TEST_SHOULD_VERIFY]
- **Passing Reference (optional):** [PASTE_PASSING_TEST_OR_LOG_IF_AVAILABLE]

## Task
1. Parse the failing test to identify every mock/stub dependency and its expected behavior.
2. Compare the mock configuration against the actual test execution to detect mismatches in:
   - **Return values:** Expected vs. actual return types, shapes, or values.
   - **Call expectations:** Expected call count, argument matchers, call order.
   - **Side effects:** Configured side effects that may not execute as expected.
   - **Lifecycle:** Setup/teardown ordering that may cause state leakage.
   - **Environment differences:** OS, filesystem, network, or timing factors that differ between local and CI.
3. For each mismatch found, classify its severity: **CRITICAL** (causes the failure), **CONTRIBUTING** (worsens flakiness), or **BENIGN** (present but unrelated).
4. Identify whether the root cause is in the **test code**, the **mock configuration**, the **production code under test**, or the **environment**.

## Output Schema
Return a JSON object with this exact structure:
```json
{
  "summary": "One-sentence root cause summary.",
  "root_cause_category": "TEST_CODE | MOCK_CONFIG | PRODUCTION_CODE | ENVIRONMENT",
  "findings": [
    {
      "severity": "CRITICAL | CONTRIBUTING | BENIGN",
      "category": "RETURN_VALUE | CALL_EXPECTATION | SIDE_EFFECT | LIFECYCLE | ENVIRONMENT",
      "location": "File:line or mock identifier",
      "expected": "What the test or mock expected.",
      "actual": "What actually occurred.",
      "fix_suggestion": "Concrete, actionable fix."
    }
  ],
  "local_vs_ci_differential": "Explanation if environment difference is the cause, otherwise null.",
  "recommended_fix_order": ["Ordered list of fix steps, most critical first."]
}

Constraints

  • Do not guess. If evidence is insufficient for a finding, mark it as INCONCLUSIVE with a note about what additional information is needed.
  • Cite specific line numbers or mock identifiers in the location field.
  • If the test passes locally but fails in CI, prioritize environment differential analysis.
  • If the test fails in both environments, prioritize mock configuration and test logic analysis.

After pasting the template, adapt it by filling in the placeholders with real data from your debugging session. The most critical inputs are the failing test code, the mock/stub configuration, and the full failure output—without these, the model cannot perform a meaningful comparison. If you have a passing reference (e.g., a similar test that works, or a previous passing run log), include it to help the model calibrate its expectations. For environment-specific failures, be precise about OS, dependency versions, and any containerization differences between local and CI. The output schema is designed to be machine-readable so you can pipe the findings directly into your issue tracker or test repair workflow. Always review the recommended_fix_order critically before applying changes—the model may suggest fixes that require human judgment about test intent and architectural trade-offs.

IMPLEMENTATION TABLE

Prompt Variables

Each placeholder must be populated for the prompt to produce reliable output. Incomplete or incorrect variables are the most common source of poor diagnosis quality.

PlaceholderPurposeExampleValidation Notes

[TEST_FAILURE_LOG]

Raw test failure output from the CI or local environment, including stack traces, error messages, and assertion failures

FAIL: test_user_creation (tests/test_auth.py:142) - AssertionError: Expected mock call not found

Must contain at least one stack trace or error message. Null or empty input should trigger an immediate abort before model invocation.

[MOCK_CONFIGURATION]

The mock or stub setup code used in the failing test, including return values, side effects, and patch decorators

mock.patch('services.payment.PaymentGateway.charge', return_value={'status': 'success'})

Parse check: must contain at least one mock.patch, MagicMock, or equivalent stub definition. If missing, the diagnosis cannot proceed.

[TEST_ENVIRONMENT]

Structured description of where the test passed and where it failed, including OS, Python version, and CI provider

PASS: local macOS 14.2, Python 3.11.4 | FAIL: GitHub Actions ubuntu-latest, Python 3.11.6

Must include both pass and fail environment descriptors. If only one environment is provided, flag as incomplete and request both.

[MODULE_UNDER_TEST]

The source code of the function or class being tested, including its imports and dependency calls

def create_user(db_session, email_service): user = User(email=email_service.send_welcome()) ...

Parse check: must be a function or class definition. If the module under test is not provided, the prompt cannot verify mock-to-real signature alignment.

[EXPECTED_BEHAVIOR]

Natural language description of what the test author intended the mock to simulate

PaymentGateway.charge should be called once with amount=99.99 and return a success status dict

Must be a non-empty string. Vague descriptions like 'it should work' should be rejected or flagged for human clarification before diagnosis.

[ACTUAL_BEHAVIOR]

What the mock actually returned or how it was actually called, extracted from the failure log or debug output

PaymentGateway.charge was called 0 times; test received AttributeError on 'status' key

Must be derived from the failure log. If actual behavior cannot be extracted, the prompt should request additional debug instrumentation.

[DEPENDENCY_SIGNATURES]

The real function signatures of mocked dependencies, used to detect signature drift between mock setup and actual API

def charge(self, amount: Decimal, currency: str = 'USD') -> Dict[str, Any]: ...

Optional but strongly recommended. If absent, the prompt should note that signature mismatch detection will be limited to call-argument analysis only.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the mock misconfiguration diagnosis prompt into a CI debugging workflow with validation, retries, and evidence grounding.

This prompt is designed to be called as part of an automated CI failure investigation pipeline or a developer CLI tool. The primary integration point is immediately after a test suite reports a failure where the discrepancy between local and CI execution suggests a mock, stub, or environment configuration issue. The application harness should collect the failing test code, the mock/stub configuration files, any relevant environment variables or CI configuration, and the full failure output before assembling the prompt.

Input assembly and validation: Before calling the model, validate that all required placeholders are populated with non-empty strings. The [FAILING_TEST_CODE] must contain the actual test function or method, not just the test name. The [MOCK_CONFIGURATION] should include the mock setup code (e.g., jest.mock, sinon.stub, unittest.mock.patch) and any fixture or factory definitions the mocks depend on. The [CI_ENVIRONMENT_VARIABLES] and [LOCAL_ENVIRONMENT_VARIABLES] should be sanitized to remove secrets before inclusion. If the test failure output exceeds 8,000 tokens, truncate it to the last 8,000 tokens and prepend a note: [Failure output truncated to last 8,000 tokens. Full output available in CI logs.]. Model choice: Use a model with strong code reasoning capabilities (e.g., Claude 3.5 Sonnet, GPT-4o) rather than a smaller or faster model, because diagnosing mock misconfigurations requires precise reasoning about test doubles, module resolution, and execution order. Set temperature to 0.0 or 0.1 to maximize deterministic, evidence-grounded output.

Output parsing and validation: Parse the model's JSON response and validate the discrepancies array. Each discrepancy object must have a non-empty evidence field that references a specific line, configuration value, or behavioral difference from the input. If any discrepancy has an empty evidence field or the root_cause_category is not one of the expected enum values (mock_return_value, stub_not_called, module_resolution, environment_difference, timing_dependency, unmocked_dependency), reject the output and retry once with an additional constraint appended: [CONSTRAINT: Every discrepancy must cite specific evidence from the provided inputs. Do not speculate without grounding.]. Retry and escalation: If the second attempt also fails validation, log the raw output and the validation errors, then escalate to a human reviewer with a pre-formatted summary of what the model produced and which validation rules failed. Do not automatically retry beyond two attempts. Logging and traceability: Log the full prompt, model response, validation result, and any retry attempts to your prompt observability system. Tag each log entry with the CI build ID and test name so that on-call engineers can correlate the diagnosis attempt with the original failure. Human review gate: For any diagnosis that recommends changing production configuration or shared test fixtures, flag the output for human review before applying the fix. The fix_suggestions array should be treated as advisory, not auto-applied, unless the change is scoped to a single test file and the suggestion includes a specific code diff that passes your existing pre-commit hooks.

IMPLEMENTATION TABLE

Expected Output Contract

Validate the structure and content of the mock misconfiguration diagnosis output before consuming it in downstream systems. Each field must pass the specified validation rule.

Field or ElementType or FormatRequiredValidation Rule

diagnosis_id

string (UUID v4)

Must parse as valid UUID v4. Reject if missing or malformed.

timestamp

string (ISO 8601 UTC)

Must parse to valid UTC datetime. Reject if timezone offset is non-zero or format invalid.

discrepancies

array of objects

Must be non-empty array. Each element must have 'mock_name', 'expected_behavior', 'actual_behavior', and 'severity' fields.

discrepancies[].mock_name

string

Must match a mock or stub identifier present in the [INPUT_CONTEXT]. Reject if name not found in source.

discrepancies[].expected_behavior

string

Must be non-empty. Should contain a concrete description of expected interaction pattern, return value, or side effect.

discrepancies[].actual_behavior

string

Must be non-empty. Should describe observed deviation. Must differ from expected_behavior by string comparison.

discrepancies[].severity

string (enum)

Must be one of: 'critical', 'high', 'medium', 'low'. Reject any other value.

discrepancies[].evidence

array of strings

Must contain at least one citation or log excerpt from [INPUT_CONTEXT]. Each string must be non-empty.

root_cause_summary

string

Must be non-empty. Should synthesize the most likely systemic cause across all discrepancies.

fix_suggestions

array of objects

Must contain at least one suggestion. Each object must have 'target_mock', 'action', and 'rationale' fields.

fix_suggestions[].target_mock

string

Must match a mock_name from the discrepancies array or a related mock in [INPUT_CONTEXT].

fix_suggestions[].action

string

Must be non-empty. Should describe a concrete configuration change, not a vague recommendation.

fix_suggestions[].rationale

string

Must be non-empty. Should explain why this action resolves the linked discrepancy.

confidence_score

number (0.0 to 1.0)

Must be a float between 0.0 and 1.0 inclusive. Reject if outside range or not parseable as float.

requires_human_review

boolean

Must be true if any discrepancy severity is 'critical' or confidence_score is below 0.7. Validate this rule on receipt.

PRACTICAL GUARDRAILS

Common Failure Modes

Mock and stub misconfigurations are among the most common causes of CI-only or environment-specific test failures. These cards cover the failure patterns that break first and how to guard against them before they reach production pipelines.

01

Environment-Specific Stub Drift

What to watch: Stubs that resolve correctly in local development but fail in CI due to differences in environment variables, network access, or service discovery. The prompt may correctly identify the mismatch but fail to detect that the stub configuration itself is environment-dependent. Guardrail: Always include environment context in the prompt input, and validate stub configurations against both local and CI environment specifications before generating a diagnosis.

02

Interaction Expectation Mismatch

What to watch: The prompt identifies that a mock expected a call that never occurred, or an unexpected call was made, but misattributes the root cause to test logic rather than mock setup. This happens when the prompt lacks visibility into the full call chain. Guardrail: Require the prompt to output both the expected interaction contract and the actual interaction trace side by side, and flag any case where the mismatch could originate from either the test or the production code under test.

03

Stale Fixture Blindness

What to watch: The prompt correctly analyzes mock configurations but fails to detect that the underlying fixtures or test data have drifted from the current schema, making the mock behavior technically correct but semantically wrong. Guardrail: Add a pre-check step that validates fixture schemas against current type definitions or API contracts before the mock diagnosis runs, and include fixture freshness as a required section in the output report.

04

Over-Mocking False Positives

What to watch: The prompt flags a mock as misconfigured when the real issue is that the test is mocking too much—hiding the actual failure behind an overly permissive stub. The diagnosis correctly identifies a discrepancy but recommends fixing the mock rather than reducing mocking scope. Guardrail: Include a heuristic check in the prompt instructions: if a mock returns a success value that would be impossible in production, flag it as a potential over-mocking issue rather than a configuration error.

05

Ordering and Lifecycle Confusion

What to watch: Mocks that pass in isolation but fail when tests run in a specific order due to shared stub state, incomplete teardown, or setup ordering assumptions. The prompt may identify the failing interaction but miss the ordering dependency. Guardrail: Require the prompt to analyze test execution order when available, and output a specific warning if any mock setup or teardown appears to depend on execution sequence rather than explicit lifecycle hooks.

06

Error Mode Simulation Gaps

What to watch: The prompt diagnoses why a mock isn't matching but fails to identify that the mock was configured only for success paths, leaving error handling, timeout, and retry behavior completely untested. The diagnosis looks correct but is incomplete. Guardrail: Extend the prompt template to explicitly check whether the mock configuration covers error modes—timeouts, connection refused, malformed responses, and rate limiting—and flag missing error simulations as a separate finding category.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the mock/stub misconfiguration diagnosis output before integrating it into a CI pipeline or team workflow. Each criterion targets a specific failure mode common to diagnostic prompts.

CriterionPass StandardFailure SignalTest Method

Discrepancy Identification

Output lists at least one specific mock/stub configuration difference between the passing and failing environments, referencing a concrete field, method, or behavior.

Output contains only vague statements like 'mocks are different' without naming a specific mock, field, or value.

Parse output for a structured discrepancy list. Assert each entry has a non-empty 'mock_name', 'field_or_behavior', and 'expected_vs_actual' field.

Environment Attribution

Each discrepancy is explicitly tagged with the environment where it was observed (e.g., 'local', 'CI', 'staging').

Discrepancies are listed without environment context, making it impossible to know which side is misconfigured.

Validate that every discrepancy object includes an 'environment' field with a value matching one of the provided environment labels.

Root Cause Classification

Output assigns a root cause category from the allowed taxonomy: 'unset_stub', 'stale_stub', 'argument_mismatch', 'call_count_mismatch', 'order_mismatch', 'network_boundary', or 'other'.

Root cause is missing, uses an undefined category, or defaults to 'other' without justification.

Check that the 'root_cause_category' field is present and its value is an exact match against the allowed taxonomy list.

Fix Suggestion Actionability

Each fix suggestion includes a specific code-level change (e.g., 'add mock for UserService.getPermissions returning []'), not just a general directive.

Fix suggestions are generic like 'fix the mock' or 'update the stub' without specifying what to change or where.

Review each fix suggestion for the presence of a target function name, a return value or behavior change, and a file or test case reference.

Evidence Grounding

Output cites at least one concrete piece of evidence per discrepancy: an error message excerpt, a log line, a stack trace frame, or a diff snippet.

Discrepancies are asserted without any supporting evidence from the provided input context.

Scan output for evidence references. Assert that each discrepancy block contains a non-empty 'evidence' field with a quoted string from the input.

Confidence Calibration

Output includes a confidence score (0.0-1.0) for each discrepancy, and high-confidence (>0.8) items are clearly distinguished from speculative ones.

All discrepancies are presented with equal certainty, or confidence scores are missing or uniformly 1.0.

Parse confidence fields as floats. Assert all values are between 0.0 and 1.0. Flag if more than 80% of scores are above 0.9 without justification.

No Hallucinated Configuration

Output does not invent mock names, file paths, or environment variables not present in the provided input context.

Output references a mock class, method, or config file that does not appear anywhere in the input test code, logs, or configuration.

Extract all mock names and file paths from the output. Cross-reference against the input context. Flag any identifier not found in the source material.

Output Schema Compliance

Output is valid JSON matching the expected schema: a top-level array of discrepancy objects with all required fields present and correctly typed.

Output is malformed JSON, missing required fields, or contains fields with incorrect types (e.g., string where array is expected).

Validate output against the JSON schema. Check required fields: 'discrepancy_id', 'mock_name', 'environment', 'expected_behavior', 'actual_behavior', 'root_cause_category', 'fix_suggestion', 'evidence', 'confidence'.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single mock framework and lighter validation. Focus on the core discrepancy detection logic without strict schema enforcement.

  • Remove the [OUTPUT_SCHEMA] constraint and let the model return a free-text discrepancy report.
  • Narrow [MOCK_FRAMEWORK] to one framework (e.g., Jest, unittest.mock, Mockito) to reduce ambiguity.
  • Replace [CI_ENVIRONMENT] and [LOCAL_ENVIRONMENT] with inline descriptions rather than structured blocks.
  • Skip the eval harness; manually spot-check 3-5 known misconfigurations.

Watch for

  • Missing schema checks causing inconsistent report structure across runs.
  • Overly broad instructions that conflate mock misconfiguration with unrelated test failures.
  • The model hallucinating framework-specific APIs when [MOCK_FRAMEWORK] is left vague.
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.