This prompt is designed for QA engineers and developers who maintain test suites and need to systematically identify anti-patterns that reduce test reliability, increase maintenance cost, and slow down CI pipelines. The job-to-be-done is a structured code review of test files—not a runtime analysis—to catch structural problems like assertion roulette, eager tests, mystery guests, test dependencies, conditional test logic, and slow test patterns before they erode suite trustworthiness. The ideal user is someone who can read test code fluently and is responsible for test suite health, whether during a pull request review, a pre-merge check, or a periodic test audit.
Prompt
Test Quality and Anti-Pattern Review Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Test Quality and Anti-Pattern Review Prompt.
Use this prompt when you have complete test file content or a focused diff of test changes as input. It expects the raw test code, not test execution logs or coverage reports. The prompt is most effective when the input includes enough context to distinguish between intentional test design choices and genuine anti-patterns—for example, a helper method that looks like a mystery guest might be a deliberate shared fixture. Do not use this prompt as a replacement for running tests, measuring actual coverage, or profiling test execution time. It analyzes structure and patterns, not runtime behavior. It is also not a general code review prompt; it is tuned specifically for test code anti-patterns and will miss non-test logic issues.
The output is a structured refactoring recommendation list, not a pass/fail verdict. Each finding should include the anti-pattern type, the specific code location, a severity rating, and a concrete refactoring suggestion. The prompt includes eval checks that force the model to justify why a pattern is flagged and to identify cases where the pattern is intentional. Before using this prompt in an automated CI gate, calibrate it against your team's test style guide and a set of known-clean and known-problematic test files. Human review remains essential for architectural decisions about test strategy, but this prompt scales the initial detection pass so reviewers can focus on judgment rather than pattern scanning.
Use Case Fit
Where the Test Quality and Anti-Pattern Review Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your workflow before integrating it into a CI pipeline or code review tool.
Good Fit: Test Suite Health Audits
Use when: QA engineers or platform teams need a systematic review of existing test files for maintainability risks. The prompt excels at scanning test code for assertion roulette, eager tests, mystery guests, and conditional logic that linters miss. Guardrail: Run on a per-file or per-directory basis to keep context focused and prevent dilution of findings across large, unrelated test suites.
Bad Fit: Runtime Flakiness Diagnosis
Avoid when: The primary goal is to debug a flaky test that only fails intermittently in CI. This prompt analyzes static test code structure, not execution traces, timing data, or environmental conditions. Guardrail: Pair with a log analysis or flaky test investigation prompt that ingests CI failure logs and execution order to diagnose non-deterministic failures.
Required Inputs
What you must provide: The full test file content, the test framework in use (e.g., Jest, pytest, JUnit), and any team-specific anti-pattern definitions or naming conventions. Guardrail: Include a [FRAMEWORK] placeholder and a [TEAM_PATTERNS] section in the prompt template so reviewers can supply framework-specific idioms and suppress false positives for accepted patterns like test helpers or shared fixtures.
Operational Risk: False Positives on Intentional Patterns
What to watch: The prompt may flag test helpers, shared setup methods, or parameterized tests as mystery guests or eager tests when they are intentional and well-documented. Guardrail: Require a human reviewer to confirm or dismiss each finding before any refactoring work begins. Add a [SUPPRESSION_RULES] input that lists accepted patterns to skip during automated scans.
Operational Risk: Over-Refactoring Without Behavior Preservation
What to watch: A refactoring recommendation list may suggest splitting or rewriting tests in ways that change what is actually being asserted, weakening the test suite's regression value. Guardrail: Always run the existing test suite before and after any prompted refactoring. Fail the refactoring PR if any previously passing test now fails or if coverage drops on the target code paths.
Variant: Pre-Merge Gating
Use when: You want to block PRs that introduce new test anti-patterns rather than reviewing legacy test suites. Guardrail: Run the prompt only on the test diff, not the full file, and configure the output to produce a simple pass/fail signal with a severity threshold. Escalate to a human reviewer only when the threshold is exceeded, keeping the merge pipeline fast.
Copy-Ready Prompt Template
A reusable prompt for identifying test anti-patterns and producing a structured refactoring recommendation list.
The following prompt template is designed to be copied directly into your AI harness, test pipeline, or IDE. It instructs the model to act as a test quality reviewer, analyzing provided test code for a specific set of known anti-patterns. The prompt is structured to produce a consistent, machine-readable JSON output that can be parsed by downstream automation, such as a CI bot that comments on merge requests or a dashboard tracking test suite health.
markdownYou are a senior test quality engineer reviewing a test suite for maintainability and reliability anti-patterns. Your task is to analyze the provided test code and identify specific instances of the following anti-patterns: - **Assertion Roulette:** Multiple assertions without explanatory messages, making failure diagnosis difficult. - **Eager Test:** A single test method that verifies multiple unrelated behaviors. - **Mystery Guest:** A test that depends on external data, files, or database state not visible within the test itself. - **Test Dependency:** Tests that must run in a specific order or rely on the side effects of other tests. - **Conditional Test Logic:** Tests containing `if`, `switch`, or loop logic that alters the verification path. - **Slow Test:** Tests with explicit waits, large data setups, or real I/O calls that are not mocked. **Input Test Code:**
[TEST_CODE]
code**Instructions:** 1. For each anti-pattern found, create a finding object in the `findings` array. 2. If no anti-patterns are found, return an empty `findings` array. 3. Provide a `refactoring_summary` that synthesizes the top 3 most critical issues into a concise, actionable paragraph. If there are no findings, state that the test code is clean. **Output Schema:** You must respond with a single valid JSON object conforming to this structure: { "findings": [ { "anti_pattern": "Assertion Roulette", "location": "test_user_update_success", "severity": "high", "evidence": "Lines 12-15 contain 4 assertions without failure messages.", "refactoring_suggestion": "Add a unique assertion message to each assertEqual call, or split into individual test methods." } ], "refactoring_summary": "The test suite has critical reliability issues. The 'test_user_update_success' method suffers from Assertion Roulette, making CI failures hard to diagnose. The 'test_full_order_flow' is an Eager Test that should be decomposed into separate unit tests for validation, payment, and notification. Finally, 'test_report_generation' is a Slow Test due to its un-mocked database calls, which will degrade pipeline performance." }
To adapt this template, replace the [TEST_CODE] placeholder with the actual test file content or a specific test method. The anti-pattern list and output schema are designed to be stable, but you can extend the anti_pattern enum values in the instructions and schema if your team has custom categories, such as 'Sensitive Data Leak' or 'Over-Mocking'. For high-risk production code, always route findings with a high severity to a human reviewer for confirmation before applying automated refactors.
Prompt Variables
Each variable must be populated before the prompt is sent to the model. Missing or malformed inputs will cause unreliable output.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TEST_CODE] | The test file or test suite source code to review for quality and anti-patterns | describe('CheckoutFlow', () => { it('works', () => { ... }) }) | Must be non-empty string. Min 50 chars. Parse check for valid code structure. Null not allowed. |
[TEST_FRAMEWORK] | The testing framework or library used in the test code | Jest 29, pytest 8.1, JUnit 5 | Must match known framework name. Used to calibrate anti-pattern detection rules. Null allowed if framework is auto-detected. |
[LANGUAGE] | The programming language of the test code | TypeScript, Python 3.12, Java 17 | Must be a recognized language identifier. Controls syntax-aware parsing. Null not allowed. |
[TEST_LEVEL] | The test level or scope being reviewed | unit, integration, e2e, component | Must be one of: unit, integration, e2e, component, contract. Affects which anti-patterns are relevant. Null defaults to unit. |
[CODEBASE_CONTEXT] | Optional surrounding production code or test utilities referenced by the tests | class CheckoutService { process() { ... } } | Null allowed. When provided, enables mystery guest detection and assertion relevance checks. String or null. |
[TEAM_STANDARDS] | Team-specific quality rules, naming conventions, or anti-pattern definitions to apply | No conditional test logic allowed. Assertions must use custom matchers from our-assertions.ts. | Null allowed. When provided, overrides default anti-pattern catalog. String with rule descriptions or null. |
[SEVERITY_THRESHOLD] | Minimum severity level to include in output | medium, high, critical | Must be one of: low, medium, high, critical. Findings below threshold are excluded from output. Defaults to medium. |
[MAX_FINDINGS] | Maximum number of findings to return | 10, 25, 50 | Must be positive integer between 1 and 100. Controls output size. Defaults to 20 if null. |
Implementation Harness Notes
How to wire the Test Quality and Anti-Pattern Review Prompt into a CI pipeline, IDE plugin, or manual review workflow with validation, retries, and human-review checkpoints.
This prompt is designed to be integrated into a software development lifecycle where test code is treated as a first-class asset. The most common integration points are a CI/CD pipeline step that runs on test file changes, a pre-commit hook for local development, or a manual review tool used by QA engineers during test suite audits. The prompt expects a complete test file or a focused diff of test changes as its primary input. Before calling the model, the harness should extract the test code, determine the testing framework in use (e.g., Jest, pytest, JUnit) from file metadata or package configuration, and inject that framework name into the [FRAMEWORK] placeholder. If the test file is large, consider splitting it into logical blocks (individual describe/test blocks) and running the prompt on each block to stay within context limits and produce more focused findings.
The implementation harness must validate the model's output against the expected JSON schema before surfacing findings. Define a strict schema that requires a findings array, where each finding has a severity (enum: CRITICAL, WARNING, SUGGESTION), an anti_pattern field matching one of the known categories (e.g., assertion_roulette, eager_test, mystery_guest, test_dependency, conditional_test_logic, slow_test), a location object with line_start and line_end integers, a description string, and a refactoring_suggestion string. If the model output fails schema validation, implement a single retry by appending the validation error to the original prompt as a correction instruction. If the retry also fails, log the raw output and flag the file for manual review rather than silently dropping findings. For high-risk test suites (e.g., financial calculations, healthcare data processing), always route CRITICAL findings to a human reviewer queue before auto-applying any refactoring suggestions.
Logging and observability are critical for tuning this prompt over time. Log the model used, prompt version, input file hash, token counts, latency, and a summary of finding counts by severity on every invocation. Track the false positive rate by having reviewers mark findings as accepted, rejected_false_positive, or rejected_not_actionable. Use this feedback to build a golden dataset of known anti-patterns and false positives for your specific codebase, which can then be used to calibrate the prompt's [EXAMPLES] section or to fine-tune a smaller model for cost efficiency. Avoid wiring this prompt directly into a merge-blocking gate until you have measured its precision on at least 50 reviewed test files and confirmed that the false positive rate is below your team's acceptable threshold. Start with a non-blocking advisory check that comments on the PR, and escalate to a blocking gate only after calibration.
Expected Output Contract
Fields, format, and validation rules for the JSON output of the Test Quality and Anti-Pattern Review Prompt. Use this contract to build validation logic in your application layer.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
findings | Array of objects | Must be an array. Can be empty if no anti-patterns are detected. | |
findings[].id | String (kebab-case) | Must match pattern ^[a-z]+(-[a-z]+)*$. Uniquely identifies the finding within the response. | |
findings[].category | Enum string | Must be one of: assertion_roulette, eager_test, mystery_guest, test_dependency, conditional_logic, slow_test, fragile_test, unclear_intent, missing_assertion, over_mocking. | |
findings[].severity | Enum string | Must be one of: critical, high, medium, low, info. | |
findings[].location | Object | Must contain file (string), line_start (integer), and line_end (integer). line_end must be >= line_start. | |
findings[].title | String | Must be 5-120 characters. Summarizes the anti-pattern concisely. | |
findings[].description | String | Must be 20-500 characters. Explains why the pattern is problematic in this specific context. | |
findings[].refactoring_suggestion | String | Must be 20-500 characters. Provides actionable, concrete steps to resolve the anti-pattern. | |
findings[].confidence | Number (0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Represents model confidence in the finding. Findings with confidence < 0.7 should be flagged for human review. | |
summary | Object | Must contain total_findings (integer), critical_count (integer), high_count (integer), and overall_assessment (string, 10-200 characters). |
Common Failure Modes
What breaks first when using the Test Quality and Anti-Pattern Review Prompt in production, and how to guard against it.
Confusing Test Intent with Anti-Pattern
What to watch: The model flags a deliberate test pattern (e.g., a shared setup method for integration tests) as a 'Mystery Guest' or 'Eager Test' anti-pattern. Guardrail: Always include a [TEST_STYLE_GUIDE] input that defines acceptable patterns for your context. Add an eval check that measures false-positive rate against a golden set of team-approved tests.
Flagging Assertion Roulette Without Context
What to watch: The model identifies multiple assertions without a clear failure message as 'Assertion Roulette' but fails to recognize that a single conceptual action is being validated. Guardrail: Instruct the prompt to distinguish between a single logical assertion with multiple checks and truly unrelated assertions. Validate output by checking that each finding includes a 'why this is a problem' rationale, not just a pattern match.
Over-Flagging Conditional Test Logic
What to watch: The model aggressively flags any if statement in a test as 'Conditional Test Logic', including simple guards for environment variables or feature flags. Guardrail: Add a [CONSTRAINTS] section to the prompt template that explicitly allows conditional logic for environment setup and feature toggles. Use a post-processing rule to suppress findings where the condition is an external configuration check.
Ignoring Performance Anti-Patterns in Small Suites
What to watch: The model flags 'Slow Test' patterns (e.g., file I/O, network calls) that are negligible in a small test suite but would be catastrophic at scale. Guardrail: Instruct the prompt to categorize findings by impact horizon: 'Immediate Problem' vs. 'Scaling Risk.' This helps the team prioritize without ignoring future technical debt.
Producing Generic Refactoring Advice
What to watch: The output contains vague suggestions like 'refactor to improve isolation' without concrete, actionable steps tied to the specific code under review. Guardrail: The prompt must require that every refactoring recommendation includes a specific code-level action (e.g., 'extract this block into a factory method and inject it') and a before/after example. Validate this with a rubric check for 'actionability.'
Missing Test Dependency Chains
What to watch: The model identifies a 'Test Dependency' but fails to trace the full chain, missing that test C depends on test B, which depends on test A's side effects. Guardrail: Instruct the prompt to analyze the entire test file or suite for shared mutable state, not just pairwise relationships. Add an eval for 'dependency chain completeness' by testing against a known suite with a 3+ step dependency chain.
Evaluation Rubric
Use this rubric to build automated eval checks and calibrate the Test Quality and Anti-Pattern Review Prompt against your team's quality standards. Each criterion maps to a pass standard, a failure signal, and a test method suitable for CI integration.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Anti-Pattern Detection Recall | All seeded anti-patterns (assertion roulette, eager test, mystery guest, test dependency, conditional test logic, slow test) are identified in the output | A known seeded anti-pattern is missing from the findings list | Run prompt against a golden test file containing one instance of each anti-pattern. Assert that each anti-pattern type appears in the output. |
False Positive Rate | Fewer than 10% of reported findings are false positives when reviewed by a senior QA engineer | A finding flags a pattern that is intentional, idiomatic, or required by the test framework | Sample 20 findings from production runs. Have a QA engineer label each as true or false positive. Calculate false positive rate. |
Code Reference Accuracy | Every finding includes a file path and line range that correctly points to the anti-pattern location | A finding references a line that does not contain the described anti-pattern or references a non-existent file | Parse output for file and line references. Use a script to verify that each referenced line exists in the input and contains the flagged construct. |
Severity Calibration | Severity ratings (Critical, High, Medium, Low) match a pre-defined team rubric within one level of a human reviewer's rating | A test with a hard dependency on external state is rated Low, or a minor naming issue is rated Critical | Create 10 test cases with pre-assigned severity labels. Compare model-assigned severity to labels. Measure exact match and within-one-level agreement rates. |
Refactoring Recommendation Actionability | Each recommendation includes a specific, concrete change that a developer can apply without further clarification | A recommendation says 'improve the test' or 'fix the dependency' without specifying what code to change or how | Extract recommendation text. Check for presence of specific code patterns, method names, or structural changes. Flag generic advice as failure. |
Output Schema Compliance | Output is valid JSON matching the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed | Output is missing required fields, contains extra untyped fields, or is not parseable JSON | Validate output against the JSON schema using a schema validator. Reject any response that fails validation. |
Explanation Groundedness | Every explanation references specific code elements from the input and states why the pattern is problematic in context | An explanation describes a general anti-pattern without connecting it to the submitted code | For each finding, check that the explanation contains at least one code token or line reference from the input. Flag explanations with zero code references. |
Test Intent Preservation | Findings distinguish between anti-patterns and intentional test design choices. No finding suggests removing a deliberate test dependency without acknowledging its purpose | A finding recommends removing a shared setup method that is intentionally shared across related test classes | Include a test file with documented intentional patterns. Verify that the output either omits these or explicitly notes their intentional nature. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single test file and lighter validation. Focus on getting the anti-pattern classification right before adding structured output constraints. Drop the [OUTPUT_SCHEMA] placeholder and ask for a plain markdown list of findings with severity labels.
Prompt snippet
codeReview the following test code for anti-patterns. Return findings as a markdown list with severity (High/Medium/Low) and a one-line explanation for each. [TEST_CODE]
Watch for
- Missing schema checks leading to inconsistent finding formats
- Overly broad instructions that flag idiomatic framework patterns as smells
- No distinction between test intent and anti-pattern when assertions look sparse

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us