Synthetic Test Data Generation With LLMs: Generate, Then Gate
qabash.comAmbassador
Nov 24, 2026
Quick answer
To generate synthetic test data with LLMs safely, ask the model for structured output (JSON matching a schema), then validate every row in code before use. The gate should check the schema and types, business rules (age limits, valid country codes), privacy (reserved test domains only, no Luhn-valid card numbers or real identifiers) and uniqueness. Reject bad rows with a reason rather than fixing them silently. Use LLMs for variety and edge cases, Faker for volume, and seeded fixtures for anything a test asserts on exactly.

Test data is where good test plans go to die. Production copies are a privacy risk, hand-written fixtures are thin, and random generators produce “John Doe, age 47” a thousand times without a single interesting edge case.
LLMs look like the answer. Ask for “200 realistic customers from 12 countries, including tricky names and edge cases” and you get them in seconds, with variety Faker can’t match.
You also get a few customers who are 15, emails on real domains, a country written as “Brazil” instead of “BR” and, now and then, something that looks like real personal data. This guide covers synthetic test data generation with LLMs the way it works in practice: generate fast, then pass every row through a validation gate before a test ever sees it.
Why use LLMs for test data at all?
Because realistic variety is expensive to hand-write. LLMs are good at:
- Plausible combinations. A German address with a German postcode format and a matching phone prefix.
- Edge cases on request. Names with apostrophes, right-to-left scripts, emoji, very long surnames, single-letter names.
- Domain realism. Insurance claims with believable descriptions, support tickets in five tones, invoices with sensible line items.
- Text fields. Free-text notes, reviews and messages, which random generators do badly.
They’re weak at volume, exact constraints and repeatability. That’s what the gate and the rest of your toolkit are for.
Faker vs LLMs vs masked production data

The usual answer is a mix. Faker for load and bulk, LLMs for variety and edge cases, small hand-written fixtures for anything a test asserts on exactly, and masked production data only where real distributions are essential and governance allows it.
What goes wrong with LLM-generated test data?
From the model’s point of view, the data only has to look plausible. Your system needs it to be valid. Typical defects:
| Defect | Example | Why it matters |
|---|---|---|
| Schema drift | "country": "Brazil" instead of "BR" |
Tests fail for the wrong reason, or pass on bad data |
| Rule violations | A 15-year-old in an adults-only product | Invalid fixtures make tests meaningless |
| Real-looking PII | Plausible emails on real domains, numbers that pass card checks | Test emails can reach real inboxes; scanners flag your repo |
| Duplicates | The same email twice in a batch | Unique constraints break setup in confusing ways |
| Mode collapse | Twenty “Priya Sharma”s in 200 rows | Less variety than you paid for |
| Truncation or broken JSON | Output cut off at a token limit | Partial batches that look complete |
None of these are rare. All of them are cheap to catch in code.
The generate-then-gate pattern

A validation gate in Python
The gate uses Pydantic for the schema, plus a few rules no schema can express. It returns accepted rows and a reason for every rejection.
# gate.py: validate LLM-generated test data before any test uses it
import json
import re
from pydantic import BaseModel, EmailStr, Field, ValidationError
class Customer(BaseModel):
name: str = Field(min_length=1)
email: EmailStr
age: int = Field(ge=18, le=120)
country: str = Field(pattern=r"^[A-Z]{2}$") # ISO 3166 alpha-2
note: str = ""
def luhn_ok(digits: str) -> bool:
"""True if the digits pass the Luhn check used by real card numbers."""
total, parity = 0, len(digits) % 2
for i, ch in enumerate(digits):
d = int(ch)
if i % 2 == parity:
d = d * 2 - 9 if d > 4 else d * 2
total += d
return total % 10 == 0
CARD_LIKE = re.compile(r"\b\d{13,19}\b")
SAFE_EMAIL_DOMAINS = ("example.com", "example.org", "test") # reserved for testing
def gate(raw_json: str) -> tuple[list[Customer], list[str]]:
"""Return (accepted rows, rejection reasons). Never silently drop data."""
accepted, rejected, seen = [], [], set()
for i, row in enumerate(json.loads(raw_json)):
try:
c = Customer(**row)
except ValidationError as e:
rejected.append(f"row {i}: schema: {e.errors()[0]['loc'][0]}")
continue
if not c.email.endswith(SAFE_EMAIL_DOMAINS):
rejected.append(f"row {i}: email not on a reserved test domain")
elif any(luhn_ok(m) for m in CARD_LIKE.findall(c.note)):
rejected.append(f"row {i}: contains a Luhn-valid card number")
elif c.email in seen:
rejected.append(f"row {i}: duplicate email")
else:
seen.add(c.email)
accepted.append(c)
return accepted, rejected
Why these checks:
- Reserved domains.
example.com,example.organd the.testtop-level domain are reserved by RFC 2606 and RFC 6761 and never deliver to real people. A test that sends email can’t spam a stranger. - Luhn check. Real card numbers pass the Luhn checksum. Rejecting any Luhn-valid number in free text keeps card-like data out of fixtures and out of your security scanner’s findings. If you need payment test cards, use your provider’s published test numbers in dedicated fixtures, not in LLM output.
- Reasons, not silent drops. Rejection reasons tell you how to fix the prompt. If half the rows fail on
country, the prompt needs an example.
Now feed it a realistic batch, defects included:
# test_gate.py: feed the gate a realistic batch of LLM output, defects included
import json
from gate import gate
LLM_OUTPUT = json.dumps([
{"name": "Asha Rao", "email": "asha.rao@example.com", "age": 34, "country": "IN"},
{"name": "Liam Chen", "email": "liam@gmail.com", "age": 29, "country": "GB"},
{"name": "Teen User", "email": "teen@example.com", "age": 15, "country": "US"},
{"name": "Ana Souza", "email": "ana@example.org", "age": 41, "country": "Brazil"},
{"name": "Card Note", "email": "card@example.com", "age": 50, "country": "DE",
"note": "paid with 4111111111111111"},
{"name": "Asha Again", "email": "asha.rao@example.com", "age": 35, "country": "IN"},
])
def test_gate_accepts_only_clean_rows():
accepted, rejected = gate(LLM_OUTPUT)
assert [c.name for c in accepted] == ["Asha Rao"]
assert len(rejected) == 5
def test_every_rejection_has_a_reason():
_, rejected = gate(LLM_OUTPUT)
assert rejected == [
"row 1: email not on a reserved test domain",
"row 2: schema: age",
"row 3: schema: country",
"row 4: contains a Luhn-valid card number",
"row 5: duplicate email",
]
pip install "pydantic[email]" pytest
pytest -q
# 2 passed in 0.14s
Five of six rows rejected, each with a reason. In a real batch the ratio is usually far better, but the point stands: without the gate, all six would have gone into your tests.
Prompting for useful test data
The gate catches bad rows. A good prompt means fewer of them. What works:
- Give the schema. Paste the JSON Schema (Pydantic can export it with
Customer.model_json_schema()) and use your provider’s structured-output mode where available. - Ask for the edge cases you want by name. “Include names with apostrophes, hyphens, non-Latin scripts and a single-character name.”
- State the safety rules. “Use only example.com, example.org or .test email domains. Never include card numbers or national IDs.”
- Ask for coverage, not just count. “At least two customers per country in this list; ages spread across 18 to 90 with some at exactly 18.”
- Generate in small batches. Smaller batches truncate less and drift less. Deduplicate across batches.
Then let the rejection reasons drive prompt fixes. That’s a feedback loop, not guesswork.
Reproducibility: keep the data, not the prompt
An LLM won’t give you the same 200 customers twice. So don’t regenerate test data on every run.
Generate once, gate, then commit the accepted rows as a versioned fixture. Tests read the fixture. When you need new data, regenerate deliberately, review the diff and commit again.
This gives you the variety of LLM data with the repeatability of hand-written fixtures. It also means a failing test can be rerun with exactly the same data, which matters a lot more than how the data was made.
Common mistakes testers make
| Mistake | Why it happens | Better approach |
|---|---|---|
| Generating data at test run time | Feels dynamic and fresh | Generate once, gate, commit as a fixture |
| Trusting the output’s format | It looked right in the sample | Validate every row with a schema |
| Repairing bad rows silently | Quicker than rejecting | Reject with reasons; fix the prompt |
| Real email domains in fixtures | The model picks common domains | Enforce reserved domains in the gate |
| Using LLM data for exact assertions | It’s realistic | Use small hand-written fixtures for exact expected values |
| Calling LLM data anonymised production data | “It’s synthetic” | If you prompt with real records, treat the output as derived personal data |
The last row deserves emphasis. If you paste real customer records into a prompt and ask for “similar” ones, the output can contain fragments of the originals. That’s not synthetic in any privacy sense. Prompt from schemas and rules, not from real data.
Interview questions
Beginner
What is synthetic test data?
Artificial data created for testing instead of copying real production data.
Why validate LLM-generated data?
Models produce plausible but sometimes invalid, duplicated or unsafe rows.
What are reserved test domains?
Domains like example.com and the .test TLD that never belong to real users.
When would you use Faker instead of an LLM?
For high volume, speed and exact repeatability with a seed.
Intermediate
Why reject rather than repair bad rows?
Rejection reasons show what the generator gets wrong, and repairs hide it.
How do you make LLM test data reproducible?
Generate once, validate, commit the accepted rows as a versioned fixture.
What is the Luhn check used for here?
Detecting numbers that would pass as real card numbers.
How do you get edge cases from an LLM?
Name them explicitly in the prompt and check coverage in the gate.
Advanced
What privacy risk comes from prompting with real records?
The output can reproduce parts of real personal data, so it isn’t truly synthetic.
How would you measure the quality of a generated dataset?
Rejection rate by reason, uniqueness, coverage of required edge cases and distribution across key fields.
How would you combine data sources in one suite?
Faker for volume, LLM data for variety, hand fixtures for exact assertions, masked production only where governance allows.
How do you test the gate itself?
Feed it known-bad rows for every rule and assert the exact rejection reasons, as in the example.
How AI changes this
Test data used to be a chore that got skipped. LLMs make realistic, varied data cheap, which removes the excuse for thin fixtures.
The risk moves rather than disappears. The hard part is no longer creating data; it’s trusting it. Teams that treat generated data like any other untrusted input, validated at the boundary, get the speed without the surprises.
Into 2027, expect more test platforms to offer built-in AI data generation and more regulators to ask how test data was produced, especially for high-risk AI systems. A gate with logged rejection reasons answers both. Automation can execute tests. Thinking still belongs to testers.
Best practices checklist
- Ask for JSON that matches a published schema
- Validate every row: schema, types and business rules
- Allow only reserved test email domains
- Reject card-like numbers and real identifiers
- Remove duplicates within and across batches
- Log a reason for every rejected row
- Commit accepted rows as versioned fixtures
- Never prompt with real customer records
Conclusion
Synthetic test data generation with LLMs is genuinely useful: realistic variety and edge cases in seconds instead of days. It’s only safe when you treat the output as untrusted input.
Generate, then gate. Validate every row, reject with reasons, keep privacy rules in code and freeze the result as a fixture. You get better data than hand-written fixtures, and you can still rerun any failing test with exactly the same inputs.
A bug found in production is expensive. A bug prevented is priceless.
Keep testing. Keep learning. Keep questioning.
Go deeper · QA Bash kit
LLM Evals Kit
Test LLM features like any other feature: a dataset, graders, an LLM judge and a CI gate.
3–6 yrs · 32 passing tests
₹999₹1,249
Rate this article
9.0/10 average · 41 ratings
Discussion
Be the first to weigh in
Your question or experience helps the next tester who reads this. Sign in and earn +25 XP for every approved comment or reply.
Written by
Keep reading




