Skip to content

operationalwrocław--:-- cet

RITE NRG

∕ insights / how-to-test-ai-generated-code.md

AI Generated Code

How to Test AI Generated Code: A Practical Workflow

Learn how to test AI generated code with a five-layer workflow covering review, tests, security checks and production gates before you ship.

>_article.meta

published
2026-11-24
reading_time
12 min read
topics
AI generated code, AI code testing, software testing, AI code security, production readiness

#01/article

How to Test AI Generated Code: A Practical Workflow

The most popular advice on how to test AI generated code is to let the model write the tests too, run the suite, and watch coverage climb. That's the fastest way to ship code that passes everything and still breaks in production, because the generated tests often encode the same wrong assumption as the generated implementation. Two artifacts, one blind spot, zero disagreement.

The business cost lands where it always lands: engineer hours spent on rework, a missed release window, an incident call nobody budgeted for, and a customer who stops trusting your product. Generation got cheap. Verification didn't. Here's the workflow I'd put in front of any team shipping AI-assisted changes, and the evidence each stage has to produce before the change moves.

A Five-Layer Workflow for Testing AI Code

A green test run isn't proof of safety. A 2025 quantitative study of 4,442 Java assignments found no direct correlation between functional pass rates and overall code quality or security, with solutions that passed functional tests still carrying SonarQube-detected bugs, vulnerabilities and code smells (arXiv study on Java assignment quality). Security exposure is just as concrete: a large empirical study of GitHub Copilot code contributions found approximately 40% of the evaluated outputs were vulnerable, with 44% containing at least one weakness mapped to a Common Weakness Enumeration (ACM study of Copilot contributions).

Treat generated output as untrusted input. We use AI where it creates measurable value and conventional software where that's simpler, safer or more economical, and the source of the code never changes the bar it has to clear.

Faster generation only creates value when verification keeps pace with it.

The five testing layers and the evidence each one must produce

Layer Question it answers Typical checks Evidence to move on
1. Review Is the change safe to read and own? Diff review, provenance record, risk tier Named reviewer and recorded prompt, model and version
2. Functional tests Does it work on expected inputs? Unit, contract and regression tests Zero unexplained test failures
3. Adversarial tests Does it fail safely on hostile inputs? Malformed payloads, boundary values, auth bypass attempts Each defect found has a regression test
4. Security checks Can the code be exploited? SAST, dependency and SBOM scans, secret detection, fuzzing No unresolved critical or high findings
5. Production readiness Can we run, monitor and roll it back? Monitoring, rollback path, runbook, documentation Telemetry live, owner named, rollback tested

Run cheap checks first, then spend human attention

The order is an economics decision, not a ritual. Formatting, compilation, type checking and linting cost seconds, so run them in parallel the moment a pull request opens. A reviewer shouldn't spend forty minutes reading a change that doesn't compile.

Then assign a risk tier and let it set the mandatory layers. Internal scripts and developer tooling sit at the low end. Authentication, billing, personal data access and external integrations sit at the high end and get every layer plus manual security review. Fast-path the low tier so the workflow protects quality without turning a two-line change into a two-day approval chain.

Review Every AI Change Before It Runs

Review comes first because a human reading the diff can catch wrong intent before a test suite locks it in. Once tests exist, they defend the implementation, and arguing with green checkmarks is much harder than arguing with a pull request.

The vulnerability rates justify reading security-sensitive paths by hand. A 2024 study of large language models generating C programs reported that at least 62.07% of the generated programs were vulnerable, and in the FormAI dataset of 112,000 C programs generated with GPT-3.5-turbo, more than 51.24% were identified as vulnerable (Empirical Software Engineering study on LLM-generated C code). Code that compiles and prints the expected output can still handle memory unsafely or skip input validation entirely.

A four-step infographic showing the manual review process for ensuring safety in AI-generated code.

Six steps before anything executes

  1. Freeze the change. Commit the generated code as-is in a reproducible commit. If the reviewer can't rebuild exactly what was generated, no later evidence means anything.
  2. Record provenance in the pull request. Prompt, model, version, dependencies and assigned reviewer. This is your audit trail when someone asks six months later why a billing rule looks the way it does.
  3. Assign the risk tier. Low for internal tooling, high for authentication, payments, personal data and external integrations. The tier decides review depth, so set it before reading a single line.
  4. Read the diff against the written specification. Ask whether it does what was asked and nothing more. Hunt for extra endpoints, hard-coded secrets, unused dependencies, swallowed exceptions and logic that changes a default without being requested.
  5. Walk the sensitive paths line by line. Authorization, input validation, cryptography and data handling. Trace one real request from entry to database and back.
  6. Require a named senior engineer to sign off and mark the change as AI-authored in version control. When AI accelerates implementation, senior engineers stay accountable for data, security, integration and production quality.

Risk tiers and the layers each one requires

Risk tier Typical changes Layers required
Low Internal scripts, reports, developer tooling Review, functional tests, production readiness
Medium Customer-facing features without sensitive data All five layers, with dependency and secret scans on every change
High Authentication, billing, personal data, external integrations All five layers, manual security review, and tests written by a different engineer or model from the spec

The common slip is reviewing style while skipping behaviour. Reviewers comment on naming and formatting, approve, and never ask what happens when the caller isn't the account owner. The accountable engineer owns the merge decision even when the code took ninety seconds to produce.

Write Tests That Challenge the Generated Code

Ask the same model to implement a refund calculation and test it, and you'll often get two expressions of one misunderstanding. Say the spec says partial refunds round down to the cent and the model rounds half up. The implementation rounds half up, the test asserts half up, the suite goes green, and finance finds the drift at month end.

Write tests from the specification before reading the generated code, or hand test authoring to a different engineer or a different model. Independence is the whole point. Our guide to AI test case generation covers how to structure that split without doubling the work.

Cover four case types, then check the suite itself

Deterministic unit tests need positive, negative, boundary and regression cases for every behaviour the change touches. Add contract tests for each API in the blast radius, including the ones the change only calls. For repository-level patches, verify both PASS_TO_PASS tests that must keep passing and FAIL_TO_PASS tests that must move from failing to passing: benchmark research on repository-level patch evaluation found 36 tasks with insufficient tests and 345 erroneous patches incorrectly labeled as passed (ACL 2025 benchmark study on test adequacy). Weak tests aren't a minor quality issue, they're a primary failure mode.

Property-based tests catch what example-based tests miss. Assert invariants instead of outputs:

  • Idempotence: applying the same operation twice leaves the same state, which matters for retries and webhook replays.
  • Conservation of value: refunds plus retained amounts never exceed the original charge, across every split.
  • Authorization boundaries: no role reaches another tenant's record, whatever identifier it supplies.
  • Error behaviour: invalid input produces a typed error, never a partial write.

Break the code on purpose

Mutation testing tells you whether your suite can detect a defect. Flip a comparison from greater-than to greater-than-or-equal, invert a boolean, delete a validation call, then run the tests. If nothing fails, that line is untested regardless of what the coverage report says.

Practical rule: set the mutation score target by risk tier, and review every surviving mutant in high-tier code by hand.

For the refund example, a mutant that changes the rounding mode should kill at least one test. If it survives, you've found the gap finance would have found for you.

Finish with the adversarial pass: malformed input, boundary values, oversized payloads and unexpected types. Run high-tier code in an isolated environment and compare its output against a trusted reference implementation or a production-like golden dataset.

Run Security Checks as a Separate Stage

Functional and adversarial tests ask whether the code behaves. They rarely ask whether a transitive dependency is exploitable, whether a role can reach an endpoint it shouldn't, or whether a secret travelled into the diff. That's a different question, and it needs its own stage with its own gate.

Don't accept the model's self-review as the security control. An empirical study of LLM-generated secure-code tasks reported vulnerability rates of 10.17% to 24.01%, compared with 4.64% for human solutions (ACM study on LLM secure-code generation). A tool that produces the weakness isn't a reliable judge of it.

A professional IT specialist reviews code on a monitor while his colleague holds a checklist nearby.

The stages, in order

  1. Threat model the change. Ten minutes with the reviewer and the author, mapping likely weaknesses to CWE categories. This decides which scanners matter and which findings you'll take seriously.
  2. Run SAST on the changed code. Semgrep or CodeQL with rules tuned to your stack beats a generic ruleset that floods the pull request with noise.
  3. Scan dependencies and generate an SBOM, then run secret detection across the diff. Transitive dependencies are where generated code imports risk, so scan the resolved tree, not just the manifest.
  4. Test API authorization explicitly. Build a matrix of every role against every endpoint the change touches, and assert the denials, not just the successes.
  5. Fuzz and run dynamic tests in a disposable environment. Never point a fuzzer at shared infrastructure or a staging database another team is using.

Our software security review process shows how these stages map onto reviewer ownership.

Triage rules that make findings actionable

Rank every finding by exploitability and business impact, not by scanner severity alone. Reproduce each high-severity finding by hand, because scanners produce false positives and false negatives in both directions. Patch, rescan until the vulnerable path is closed, and keep the original and remediated artifacts for audit.

Two habits sink this stage: letting generated tests define the specification, and reporting vulnerability counts as one raw number without splitting by language or task. Add a regression test for every defect you close, so the same weakness can't return in the next generated change.

Warning Signs That Your Testing Is Not Working

Teams rarely notice their testing has gone soft until a release fails. The earliest symptom is a high pass rate paired with very few real defects caught before merge. When a suite never argues with the implementation, it's usually because the tests were written to restate it.

Read the table as a diagnostic, not an accusation. Each symptom has a mechanical cause and a first fix, and the difference between them tells you whether you need one sprint or a process change.

Testing symptoms, likely causes and the fix to apply first

Symptom Likely cause First fix
Suite is green but mutation score is low Tests check outputs without checking invariants Add property tests and set a mutation target per risk tier
Coverage is high but edge cases fail in production Generated tests only cover the happy path Add boundary, negative and adversarial cases from the spec
Security scan is clean but incidents continue Scanner used as the only control Add threat modeling and manual review of auth and data paths
Generated tests change every time the prompt changes Tests were written to fit the implementation Write tests from the spec before reading the generated code
Vulnerability count looks stable but risk is rising Counts reported without language or task split Stratify findings by severity, language and component

Two of these are single-sprint work. Adding boundary and negative cases from the spec is a backlog item, and stratifying findings by severity, language and component is a dashboard change. The other three need a process decision: standing threat modeling, risk tiers on every change, and test generation that's independent of the implementation.

If your tests never fail, they aren't testing. They're agreeing.

Pick the symptom your team recognises most and make its fix the goal of the next sprint. One measurable change beats a quality initiative nobody owns, and you'll know within two weeks whether the suite started catching things it used to wave through.

Confirm Production Readiness Before You Ship

Faster generation only pays off if releases stay stable. The 2024 DORA research reported that increased AI adoption was associated with an estimated 1.5% decrease in delivery throughput and a 7.2% reduction in delivery stability, and found that 39% of respondents had little or no trust in AI-generated code (Google Cloud's announcement of the 2024 DORA report). If coding speeds up while rollbacks and incidents multiply, the business loses capacity instead of gaining it.

Track throughput and stability next to defect escape rate, change-failure rate, open security findings and time spent repairing generated code. That's the measurement model that tells you whether AI is earning its place in your delivery process.

A checklist infographic outlining five essential steps to ensure production readiness before shipping AI-generated code deployments.

The release gate

  1. Zero unexplained test failures.
  2. Mutation score met for the assigned risk tier.
  3. Reproducible build from the frozen commit.
  4. No unresolved critical or high security findings.
  5. Independent reviewer sign-off.
  6. A regression test for every defect found.
  7. Monitoring and alerts live before traffic shifts.
  8. A tested rollback path, not a documented one.
  9. A named owner for escalation.

Risk, regulation and operating ownership belong at the front of the work, not the end. We assess data reality, quality and access early, and define risk, regulation and operating ownership up front, so nobody discovers a compliance constraint the week before go-live. Where AI runs in production, the controls extend to access boundaries for models and data, human approval steps with explicit exception handling, auditability of prompts and actions, and monitoring after launch.

Here's how the gate fits into a delivery pipeline in practice.

One step you can take this week

Audit your last three AI-assisted releases against those nine items and name the first gap to close. Our prototype-to-production delivery checklist gives you the same gate in a form you can drop into a pull request template. If an AI-built application has stalled before release, a production recovery assessment reviews the code, architecture, data and security position, stabilizes what's viable, and prepares a controlled path to production with tests, monitoring and documentation.


Rite NRG builds and rescues business-critical software with senior engineers who own the merge decision, the security review and the release evidence, not just the code. If your AI-assisted changes are passing tests and still costing you incident hours, we'll audit your last releases against this workflow and show you exactly which gate is missing. Visit Rite NRG to talk through your delivery process with an engineer who'll tell you plainly what needs fixing first.

/ about the author

Written by the RITE NRG editorial team — the architects, engineers and delivery leads who build and operate AI-era software for our clients.

Technology Talent & Teams

IT Partnership Models: How to Choose the Right One

A decision-maker's guide to IT partnership models: what each model actually transfers to the partner, what it costs beyond the rate card, and how to match the model to your situation.

More guidance: all insights articles

Get a Free 30-Minute Scoping Call

Tell us about the system or idea behind this article. We tell you honestly if it is a fit — and what a fixed-scope delivery could look like.