Testing AI-Generated Code: A QA Checklist for Vibe-Coded Apps
AI-written code looks right and still fails on boundaries, rounding and page reloads. Test it in three layers against the requirement, with a checklist you can use today.
Hely PatelHead of Product and Marketing18 min read
To test AI-generated code, test it against the requirement, not against itself. Write the expected behaviour from the specification first, then check the code with three layers: example tests that cover each requirement and its boundaries, property and differential tests that compare the code with an independent reference across thousands of inputs, and a browser check for the things users actually touch, such as keyboard access, accessibility and state after a reload. AI-written code usually looks correct and often runs on the first try, which is exactly why it needs this kind of testing.
The scale of the issue is now measurable. Veracode tested more than 100 language models on 80 coding tasks and found that 45 percent of the generated code introduced a security flaw, with cross-site scripting defences failing in about 86 percent of the relevant samples. CodeRabbit analysed 470 open source pull requests and found AI-authored changes carried about 1.7 times as many issues as human ones, with logic and correctness issues leading the gap. The code is not worse because the models are careless. It is because the code is plausible by construction: it matches the shape of correct code, and the defects hide in details such as boundaries, rounding and missing states.
This guide gives you the failure patterns to look for, a three-layer method, real results from a worked example and a checklist you can use on a vibe-coded app or an AI pull request tomorrow.
Why AI-Generated Code Needs Different Testing
AI-written code fails differently from hand-written code.
A human developer who is unsure about a rule usually leaves a visible sign: a question in the ticket, a TODO, a hesitant variable name. A language model produces a confident answer either way. It fills any gap in the specification with the most common pattern from its training data. That pattern is right most of the time and wrong in ways that are easy to read past.
Three properties follow, and they shape how you test:
Plausible, not verified. The code compiles, runs and looks tidy. Reading it feels like confirmation, so reviewers approve what they would have questioned in a hurried human pull request.
Gaps filled by habit. Boundaries, empty states, error handling and rounding get the statistically common treatment rather than the one your specification asked for.
Tests that agree with the code. If you ask the same assistant to write the tests, they often encode the code's behaviour, bugs included. A test suite that was derived from the implementation cannot find the implementation's mistakes.
The last point is the one QA can fix most directly. The expected result must come from the requirement and an independent source, never from the code under test.
The 10 Failure Patterns to Look For
These patterns appear repeatedly in AI-written code. Use them as a review lens before you write a single test.
An import for a package that does not exist or is unmaintained
Verify every new dependency exists and is trusted
10
Happy path only
No handling for timeouts, empty results, duplicates
Negative and failure injection tests
Patterns 1 to 7 are demonstrated with real runs in the rest of this guide. Patterns 8 to 10 are covered in the checklist near the end. A short note on pattern 9: models can recommend package names that do not exist, and attackers can register those names. Check every new dependency by hand before it goes anywhere near your build.
The Worked Example: An Order Total
We use a requirement that every test engineer recognises, because the bugs live in the details. This is the specification we treat as the source of truth:
Order total (the requirement given to the AI assistant)
REQ-1 Each item has a unit price (in rupees, two decimals) and a quantity of 1 to 10. Anything else is rejected with ValueError.
REQ-2 Subtotal is the sum of price times quantity.
REQ-3 Coupons: SAVE10 takes 10% off the subtotal, SAVE20 takes 20% off. Codes are not case sensitive. An unknown code is rejected with ValueError.
REQ-4 Tax is 18% of the subtotal after the discount.
REQ-5 Shipping is Rs 50, and free when the subtotal after discount is Rs 500 or more.
REQ-6 Total = discounted subtotal + tax + shipping, rounded to two decimals, half up.
REQ-7 An empty cart has a total of 0.00 (no shipping).
Seven short rules. A first draft of the implementation, in the style assistants commonly produce, looks reasonable at a glance:
"""Order total calculator (illustrative first draft, written the way AI assistants commonly
answer a short spec: plain floats, minimal validation, round() at the end)."""
COUPONS = {"SAVE10": 0.10, "SAVE20": 0.20}
TAX_RATE = 0.18
FREE_SHIPPING_FROM = 500
SHIPPING = 50
def order_total(items, coupon=None):
if not items:
return 0.0
subtotal = 0
for price, qty in items:
if qty < 1 or qty > 10:
raise ValueError("quantity must be 1 to 10")
subtotal += price * qty
discount = 0
if coupon:
if coupon not in COUPONS:
raise ValueError("unknown coupon")
discount = subtotal * COUPONS[coupon]
discounted = subtotal - discount
tax = discounted * TAX_RATE
shipping = 0 if discounted > FREE_SHIPPING_FROM else SHIPPING
return round(discounted + tax + shipping, 2)
If you read it quickly you will approve it. It handles coupons, tax, shipping and rounding, and a quick manual check works: one item at Rs 1,000 with SAVE10 gives Rs 1,062.00, which is correct.
Now read it as a tester. Look at the shipping line, the coupon lookup, the money type and the validation. We will find each problem with a test rather than by reading, because that is the habit that scales.
Layer 1: Example Tests From the Requirement
The first layer is one test per requirement, plus the boundaries. The expected values are worked out by hand from the specification, never copied from the code's output.
Case-insensitive coupons (REQ-3). The code looks up save10 in a dictionary of uppercase keys, so a customer who types the code in lowercase sees "unknown coupon".
Negative price (REQ-1). The code validates quantity but never checks the price. A price of minus 100 produces a negative subtotal and a refund-shaped total.
Free shipping exactly at the threshold (REQ-5). The requirement says Rs 500 or more. The code uses >. A cart worth exactly Rs 500 after discount pays Rs 50 shipping and totals Rs 640.00 instead of Rs 590.00.
The third one is the classic boundary bug, and no amount of reading would have surfaced it unless the reviewer happened to compare > with "or more" word for word. The test found it in one run, because we deliberately tested the boundary value itself.
Layer 2: Property and Differential Tests
Example tests check the cases you thought of. The second layer checks thousands of cases you did not, using two techniques.
Property-based testing states a rule that must hold for every input and lets a tool such as Hypothesis generate the inputs. Examples of properties for the order total: the total is never negative, it has at most two decimals, and the order of the items does not change it.
Differential testing compares the code under test with an independent implementation of the same specification, called a reference or oracle. If the two ever disagree, one of them is wrong, and the failing input tells you which. The reference is deliberately simple and written with the safest tools, here Python's Decimal for money.
"""Independent oracle: the same spec written with Decimal and explicit validation."""
from decimal import Decimal, ROUND_HALF_UP
def ref_total(items, coupon=None):
if not items:
return Decimal("0.00")
sub = Decimal("0")
for price, qty in items:
if not (1 <= qty <= 10) or Decimal(str(price)) < 0:
raise ValueError
sub += Decimal(str(price)) * qty
rates = {"SAVE10": Decimal("0.10"), "SAVE20": Decimal("0.20")}
if coupon is not None:
code = coupon.upper()
if code not in rates:
raise ValueError
sub -= sub * rates[code]
tax = sub * Decimal("0.18")
ship = Decimal("0") if sub >= 500 else Decimal("50")
return (sub + tax + ship).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
"""Layer 2: properties and a differential test against reference.py (Decimal)."""
from decimal import Decimal
from hypothesis import given, settings, strategies as st
import importlib, os
order_total = importlib.import_module(os.environ.get("IMPL", "checkout")).order_total
from reference import ref_total
price = st.decimals(min_value="0.01", max_value="2000", places=2).map(float)
item = st.tuples(price, st.integers(1, 10))
cart = st.lists(item, min_size=1, max_size=6)
code = st.sampled_from([None, "SAVE10", "SAVE20", "save10", "Save20"])
@settings(max_examples=500, deadline=None)
@given(cart, code)
def test_matches_decimal_reference(c, k):
assert Decimal(str(order_total(c, k))) == ref_total(c, k)
@settings(max_examples=300, deadline=None)
@given(cart, code)
def test_total_is_never_negative_and_has_two_decimals(c, k):
t = order_total(c, k)
assert t >= 0 and round(t, 2) == t
@settings(max_examples=300, deadline=None)
@given(cart)
def test_coupon_never_increases_total_when_shipping_unchanged(c):
base = ref_total(c)
with_coupon = ref_total(c, "SAVE10")
sub = sum(Decimal(str(p)) * q for p, q in c)
if sub * Decimal("0.9") >= 500 or sub < 500: # shipping does not flip
assert with_coupon <= base
@settings(max_examples=300, deadline=None)
@given(cart, code)
def test_item_order_does_not_matter(c, k):
assert order_total(c, k) == order_total(list(reversed(c)), k)
Three more of the six failures came from this layer: the differential test against the reference, the two-decimal property and the item-order property. Reading the failure output shows what each one caught first. The generator included lowercase coupon codes, and the draft rejects them with an error, so the properties tripped on the coupon bug before anything else. That is a useful lesson in itself: a failing property tells you something is wrong, and the shrunk failing input (here a single item at Rs 0.01 with the code save10) tells you what.
Floating point has its own effect on order. Adding the same prices in a different order can change a float total by a tiny amount. To measure it alone, we ran 200,000 seeded random carts with valid codes only and compared each total with the total of the reversed cart. 135 of them differed. It is rare, and it is exactly the kind of defect no human would think to write an example for.
Isolating the float bug
The coupon bug also hid the rounding problem behind it in the differential test. To measure the rounding problem alone, we ran a separate seeded scan of 200,000 random carts using valid coupon codes only, and excluded carts where the discounted subtotal lands exactly on Rs 500, which is the shipping boundary bug again.
"""How often does the float draft differ from the Decimal reference, apart from the known
boundary and case bugs? Random carts, seeded, valid codes only, discounted subtotal != 500."""
import random
from decimal import Decimal
import importlib, os
order_total = importlib.import_module(os.environ.get("IMPL", "checkout")).order_total
from reference import ref_total
rnd = random.Random(2026)
N, diff, examples = 200_000, 0, []
for _ in range(N):
cart = [(round(rnd.uniform(0.01, 2000), 2), rnd.randint(1, 10)) for _ in range(rnd.randint(1, 5))]
code = rnd.choice([None, "SAVE10", "SAVE20"])
ref = ref_total(cart, code)
sub = sum(Decimal(str(p)) * q for p, q in cart)
if code: sub = sub * (Decimal("0.9") if code == "SAVE10" else Decimal("0.8"))
if sub == 500: continue
got = Decimal(str(order_total(cart, code)))
if got != ref:
diff += 1
if len(examples) < 3: examples.append((cart, code, float(got), float(ref)))
print(f"{diff} of {N} random carts differ ({diff/N:.3%})")
for e in examples: print("example:", e)
745 of 200,000 carts, or 0.372 percent, were off by one paisa. That sounds small. At a thousand orders a day it is about four wrong invoices daily, each of which fails a reconciliation. And you can reproduce it by hand with a single item:
Input
Exact arithmetic
Draft returns
Correct answer
One item at Rs 0.75, no coupon
0.75 + 0.135 tax + 50 shipping = 50.885
50.88
50.89
The exact total is 50.885. The requirement says to round half up, so the answer is 50.89. The float version stores 50.885 as a number just below it and rounds down to 50.88. This is why money belongs in Decimal or in integer paise, and why a differential test against a Decimal reference is worth writing for any calculation that touches money, tax or discounts.
Layer 3: Check the Browser Like a User
Most AI-built apps are shipped as a front end. The first two layers cover logic. The third covers what the user touches, and AI-generated interfaces have a consistent set of gaps here.
We built a small cart page in the first-draft style, with in-memory state, a clickable div as the Apply button and an input with only a placeholder. Then we wrote a Playwright check with five steps: state survives a reload, a lowercase coupon works, a known total is correct, the Apply control can be reached by keyboard, and an automated accessibility scan with axe-core passes.
The results on the draft page and on the fixed page:
== cart.html
reload: total before Rs 474.80, after Rs 120.00, FAIL (state lost)
lowercase coupon: "Invalid coupon" FAIL
qty 5 total Rs 708.00 (expect Rs 708.00, free shipping) PASS
keyboard reaches Apply: FAIL
axe violations: 3
- label (critical): 1 element(s)
- landmark-one-main (moderate): 1 element(s)
- region (moderate): 4 element(s)
== cart-fixed.html
reload: total before Rs 432.32, after Rs 432.32, PASS
lowercase coupon: "Coupon applied" PASS
qty 5 total Rs 708.00 (expect Rs 708.00, free shipping) PASS
keyboard reaches Apply: PASS
axe violations: 0
Check
First-draft page
Fixed page
Total survives a reload
Fail: total went from Rs 474.80 to Rs 120.00
Pass
Lowercase coupon accepted
Fail: "Invalid coupon"
Pass
Quantity 5 total (expected Rs 708.00, free shipping)
Pass
Pass
Apply reachable by keyboard
Fail
Pass
axe-core violations
3: a missing label (critical), no main landmark, content outside landmarks
0
Look at the third row. The page computed a correct total for that scenario, so a tester who only checked totals would have passed it. Everything else that failed was invisible to a total-based check: the user loses their cart on refresh, a keyboard user cannot apply a coupon at all and a screen reader user meets an unlabelled field.
The fixes were small, and an assistant can make them once told what to fix: store state in sessionStorage, use a real <button>, add a <label>, wrap the content in <main> and add an aria-live region for the coupon message. A short note on scope: an automated scan finds a portion of accessibility problems, not all of them. Treat zero axe violations as a floor, and add a manual keyboard and screen reader pass for anything customer-facing.
The Fix, and Proof That It Works
The corrected implementation uses Decimal, rounds half up, uses >= at the threshold, normalises the coupon and validates every input:
"""Order total calculator after the fixes found by the three test layers."""
from decimal import Decimal, ROUND_HALF_UP
COUPONS = {"SAVE10": Decimal("0.10"), "SAVE20": Decimal("0.20")}
TAX_RATE = Decimal("0.18")
FREE_SHIPPING_FROM = Decimal("500")
SHIPPING = Decimal("50")
def order_total(items, coupon=None):
if not items:
return 0.0
subtotal = Decimal("0")
for price, qty in items:
price = Decimal(str(price))
if price < 0 or isinstance(qty, bool) or not isinstance(qty, int) or not 1 <= qty <= 10:
raise ValueError("price must be 0 or more and quantity 1 to 10")
subtotal += price * qty
if coupon is not None:
code = coupon.strip().upper()
if code not in COUPONS:
raise ValueError("unknown coupon")
subtotal -= subtotal * COUPONS[code]
tax = subtotal * TAX_RATE
shipping = Decimal("0") if subtotal >= FREE_SHIPPING_FROM else SHIPPING
return float((subtotal + tax + shipping).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
17 passed in 1.17s
All 17 tests pass, and the 200,000-cart scan now reports zero differences:
0 of 200000 random carts differ (0.000%)
Notice the order of work. We did not fix by guessing. Each fix was driven by a failing test that cited a requirement, and each is covered permanently. That is the point of the exercise: the tests stay, and the next time anyone, human or AI, edits this function, the same seven rules are enforced.
What to Do When the Assistant Writes the Tests
It is common and reasonable to ask an assistant to write tests. Do it, with guardrails.
Give it the specification, not the code. Ask for tests from the requirement first, then show the code. Tests written while looking at the implementation tend to confirm it.
Ask for boundaries explicitly. Name the techniques: boundary value analysis and equivalence partitioning.
Check that the expected values are independent. If an expected value was obtained by running the code, it proves nothing.
Run a mutation check. Change >= to > and see if any test fails. A test suite that does not notice the change is not protecting that line.
Review the tests like production code. A passing test is only as good as its assertion. Look for tests that assert nothing meaningful or that mock away the thing under test.
The QA Checklist for AI-Generated Code
Use this on a vibe-coded app, a prototype handed to QA or an AI-authored pull request.
Before reading the code
[ ] Is there a written requirement with numbered rules? If not, write one first.
[ ] Are the expected results taken from the requirement rather than from running the code?
Logic
[ ] Every boundary in the requirement has a test at the boundary value and one on each side.
[ ] Calculations involving money, tax, discounts or percentages are compared with a Decimal or integer reference.
[ ] Inputs are tested in upper case, lower case, padded with spaces and empty.
[ ] Invalid classes are tested: negative, zero, too large, null, wrong type.
[ ] Empty, single and maximum collections are covered.
Interface
[ ] Reload the page mid-flow and confirm the state is kept or the loss is intended.
[ ] Complete the main flow with the keyboard only.
[ ] Run an automated accessibility scan, then a manual pass for customer-facing pages.
[ ] Check error and empty states, not only the happy path.
Security and supply chain
[ ] Every new dependency exists, is maintained and was added on purpose.
[ ] No secrets, tokens or keys in the code or in the prompt history committed to the repository.
[ ] Queries are parameterised and output is escaped. Run your normal security tests, since flaws such as cross-site scripting are among the most common in generated code.
[ ] Permissions and CORS settings are narrow, not wide open for convenience.
Resilience
[ ] Timeouts, retries, duplicates and partial failures are tested with injected faults.
[ ] Logging does not capture personal or payment data.
Process
[ ] A property or differential test exists for the riskiest calculation.
[ ] The suite catches a deliberate mutation of a boundary.
[ ] The tests that found bugs stay in the repository as regression tests.
How This Fits Into a Team Workflow
Testing AI-written code works best as a routine, not a one-off audit.
At prompt time: put the numbered requirement into the prompt, so the assistant sees the same rules the tests will enforce.
At review time: reviewers use the failure pattern table as a lens, and ask for the tests that cover each pattern.
In the pipeline: run example, property and differential tests on every pull request, plus a browser check on UI changes.
After release: feed escaped defects back as new tests and as new rows in your team's pattern list.
You can also package the review habits as a skill, so every assistant on the team loads the same checklist and runs the same checks. The guide to agent skills for QA shows how to build one with a script that checks the output.
Frequently Asked Questions
How do you test AI-generated code?
Test it against the requirement rather than against the code. Write expected results from the specification, cover each rule and boundary with example tests, add property and differential tests to cover inputs you did not think of, and check the user interface in a browser for keyboard access, accessibility and state handling.
Why does AI-generated code have bugs if it looks correct?
It is generated to look like correct code, and gaps in the specification are filled with the most common pattern. Boundaries, rounding, empty states and validation are the places where the common pattern differs from the requirement. Independent studies, such as Veracode's analysis of more than 100 models, found security flaws in 45 percent of generated code samples.
Can AI write its own tests?
Yes, with guardrails. Provide the specification instead of the code, ask for boundary and equivalence tests by name, confirm the expected values did not come from running the implementation and verify that the suite fails when you deliberately break a boundary. Tests that mirror the implementation prove nothing.
What is differential testing?
It compares the code under test with a simple independent implementation of the same specification and fails whenever they disagree. In our example, a Decimal reference found a one-paisa rounding error that appeared in 745 of 200,000 random carts and that no hand-written example had covered.
What should QA check first in a vibe-coded app?
Check the requirement, then the boundaries, then money and rounding, then reload and keyboard behaviour. These five areas produced every failure in our worked example, and none of them is visible from a quick demonstration.
Is an accessibility scan enough for AI-generated UI?
No. An automated scan such as axe-core finds a portion of issues quickly and is a good floor, and our fixed page passed with zero violations. Keep a manual keyboard and screen reader pass for customer-facing pages.
Does code review still matter?
Yes, but review needs a lens. Reviewing for the ten failure patterns, and asking for the test that proves each one is covered, is more reliable than reading for general correctness.
Conclusion
AI-written code earns its speed only when the testing keeps pace. The method is simple to state and effective in practice: write the requirement as numbered rules, test it in three layers and keep every failing case as a permanent regression test. In our worked example, seven rules and 17 tests exposed six defects that a quick read and a demo had both approved, and the same suite now guards the code against the next change.
Use the ten patterns as a lens, the checklist as a routine and the independent reference as your source of truth. The assistant can write the code and even help with tests. The requirement, and the judgment about what counts as correct, stays with the tester.
Key Takeaways
Test AI-generated code against the requirement, never against itself. Expected results must come from the specification or an independent reference.
AI code is plausible by construction. Veracode found security flaws in 45 percent of code samples across more than 100 models, and CodeRabbit measured about 1.7 times more issues in AI-authored pull requests.
Use three layers: example tests with boundaries, property and differential tests, and a browser check for keyboard access, accessibility and reload behaviour.
In our worked example, the first draft failed 6 of 17 tests. Three came from examples (case-sensitive coupon, negative price, > where the rule said "or more") and three from property and differential tests.
Float money produced a wrong paisa in 745 of 200,000 random carts (0.372 percent), and 135 of 200,000 carts gave a different total when the items were reversed. A single item at Rs 0.75 returns 50.88 instead of 50.89.
The draft page computed a correct total yet lost the cart on reload, hid Apply from the keyboard and had 3 accessibility violations. The fixed page has none.
Keep every test that found a bug. It becomes the regression suite for the next AI change.
Hely PatelHead of Product and Marketing @AIdriventesting.ai. Leads the platform's AI testing tools from idea to launch, and writes about AI-driven testing and practical AI adoption for QA teams.