Skip to content
Tutorials

Generating Realistic Test Data: Faker Factories, Seeding, Volume and Privacy

AIDToolStack EditorialNovember 7, 20267 min read
TestingFakerTest DataPrivacy
Share:Twitter

Test data goes wrong in two opposite ways. Either it's so fake (test1, test2, [email protected]) that the UI never meets a long surname, an apostrophe or a customer with 4,000 orders, or someone copies the production database "just for staging" and now real people's details live on a laptop. The goal is data that behaves like production without being production.

This post covers the generator libraries (with current versions as of November 2026), how to make generated data reproducible, how to produce volume inside the database, and what the privacy rules say about copying real data.

Decision chart matching unit tests, end-to-end tests, volume testing and real-world edge cases to a source of test data
Decision chart matching unit tests, end-to-end tests, volume testing and real-world edge cases to a source of test data

The libraries

Two Faker libraries cover most stacks:

@faker-js/fakerFaker (Python)
Current version10.6.0, released 14 August 2026 per the npm registry40.44.0, released 28 October 2026
RuntimeNode ^20.19.0, ^22.13.0, ^23.5.0 or >=24 (package engines field); ESM only since v10.0.0Python 3.10 or later
Locales"more than 70" prebuilt instances, e.g. fakerDEpass a locale or a list, e.g. Faker(['it_IT', 'en_US', 'ja_JP'])
Seedingfaker.seed(123)Faker.seed(4321) or fake.seed_instance(4321)
Test runner hooknone built ina pytest plugin with a faker fixture and a faker_seed fixture

If you're on CommonJS and stuck there, note the ESM-only change: the v10 release notes point CJS users to the migration guide.

A factory, not a pile of random calls

Scattering faker.person.fullName() through test files gives you tests that pass on Tuesday and fail on Wednesday. Put generation behind one factory per entity and let each test override what it cares about:

import { faker } from '@faker-js/faker';

faker.seed(20261107);
faker.setDefaultRefDate('2026-11-01T00:00:00.000Z');

type Plan = 'free' | 'pro' | 'team';
type User = { id: string; name: string; email: string; plan: Plan; createdAt: Date };

export function makeUser(overrides: Partial<User> = {}): User {
  const firstName = faker.person.firstName();
  const lastName = faker.person.lastName();
  return {
    id: faker.string.uuid(),
    name: `${firstName} ${lastName}`,
    email: faker.internet.exampleEmail({ firstName, lastName }),
    plan: faker.helpers.weightedArrayElement<Plan>([
      { weight: 7, value: 'free' },
      { weight: 2, value: 'pro' },
      { weight: 1, value: 'team' },
    ]),
    createdAt: faker.date.past({ years: 2 }),
    ...overrides,
  };
}

const users = faker.helpers.multiple(() => makeUser(), { count: 50 });
const admin = makeUser({ plan: 'team', email: '[email protected]' });

A few choices in there are deliberate:

  • exampleEmail instead of email. By default faker.internet.email() picks a random free mail provider, so your seed data can contain addresses that look deliverable. exampleEmail uses example domains (the docs show example.com and example.net), which RFC 2606 reserves for exactly this. For hand-written fixtures I use .test, which the same RFC reserves for testing.
  • Weighted plans. Uniform randomness is unrealistic. Real data is skewed, and skew is what exposes slow queries and lopsided layouts. weightedArrayElement takes explicit weights.
  • The test asserts on overrides. If a test checks that team users see billing settings, it passes plan: 'team' itself instead of hoping the random draw cooperates.

The Python version has the same shape: one function per model, Faker.seed() once, keyword overrides. In pytest, override the plugin's faker_seed fixture rather than calling seed() in each test.

Reproducibility has three parts

Seeding alone isn't enough. To get the same data on every machine and every run:

  1. Seed once, at a known point. Calling faker.seed(123) again restarts the sequence. Seeding per test file keeps one test's extra calls from shifting another's data.
  2. Fix the reference date. Methods like date.past count back from "now", so a seed alone gives different dates tomorrow. faker.setDefaultRefDate(...) or a refDate option pins it.
  3. Pin the library version. Both projects say seeded output can change between releases. Faker.js warns that upgrading "may get different values for the same seed", and the Python docs say results aren't guaranteed consistent across patch versions. Lockfiles handle this, but expect a snapshot diff when Dependabot bumps Faker, and don't write assertions on generated values you didn't set.

Uniqueness is the other trap. The Faker.js guide is blunt that its methods do not return unique values. For emails or usernames that hit a UNIQUE constraint, append a sequence number or use faker.helpers.uniqueArray. Python's fake.unique.email() tracks values for you and throws UniquenessException when it runs out.

Volume belongs in the database

For 100,000 rows to test pagination or check an index, don't generate a giant SQL file in JavaScript. Let the database make the rows. In SQLite (I ran this; it took about a tenth of a second on a laptop):

CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE,
                    plan TEXT NOT NULL, created_at TEXT NOT NULL);

WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100000)
INSERT INTO users (id, email, plan, created_at)
SELECT i,
       'user' || i || '@example.test',
       CASE WHEN i % 100 = 0 THEN 'team' WHEN i % 10 = 0 THEN 'pro' ELSE 'free' END,
       date('2026-11-01', '-' || (i % 730) || ' days')
FROM n;

SELECT plan, COUNT(*) AS users FROM users GROUP BY plan ORDER BY users DESC;
plan  users
----  -----
free  90000
pro   9000
team  1000

In Postgres, replace the recursive CTE with generate_series(1, 100000) and the date() call with date '2026-11-01' - (i % 730). The modulo arithmetic is deterministic, so you get the same table every time, and you control the skew exactly. Then run EXPLAIN ANALYZE against data that's actually big enough to make the planner choose an index.

Browser tools for quick jobs

For a one-off fixture or a demo table, our generators save writing a script. Know what each one does before you rely on it:

  • Seed Data Generator: define columns (thirteen types, including foreign keys with a max ID) and get a multi-row INSERT for up to 100 rows. It uses a fixed seed, so the same setup gives the same rows. The dialect selector doesn't change the output.
  • Test Data Generator: five templates (users, products, addresses, companies, transactions), 1 to 100 records as JSON, CSV or SQL. It uses Math.random, so every click gives new data.
  • JSON Schema Faker: paste a JSON Schema and get up to 50 samples that respect required, enum, min/max and a handful of string formats. Handy for mock API responses.
  • Faker Playground: small built-in word lists across eight categories, for when you just need a few believable values.

One caveat I found reading their source: the Test Data Generator, Seed Data Generator and Faker Playground all build some emails at real webmail domains such as gmail.com and outlook.com. That's fine for a table on screen. Before those rows reach anything that can send email, rewrite the domains to example.test.

Copying production: what the law actually says

Sometimes generated data can't reproduce a bug, and someone suggests a masked copy of production. Know what you're signing up for. Under the GDPR, data that has been pseudonymised but could be attributed to a person using additional information is still treated as information about an identifiable person (Recital 26). Only truly anonymous data falls outside the regulation. Pseudonymisation is still worth doing, since Recital 28 says it "can reduce the risks to the data subjects concerned", but a masked staging copy is personal data with all the obligations that brings: access control, retention, breach reporting. The EDPB has also published draft guidelines on pseudonymisation (01/2025), consulted on in early 2025, that go into the techniques.

In practice, masking is harder than it looks. Our Data Masking Tool shows the limits of pattern matching nicely: it finds emails, phone numbers, US SSNs, card numbers and IPv4 addresses by regex, but names, street addresses and free-text notes pass straight through. Free-text columns (support tickets, delivery instructions) are where real personal data hides.

My order of preference:

  1. Reproduce the shape, not the people. Look at the production row that triggers the bug, then write a factory override that recreates its structure: the 400-character name, the null middle field, the emoji in the address.
  2. Generate volume in-database to match production's row counts and skew.
  3. Only if those fail, use a minimised, pseudonymised extract of the specific rows involved, kept somewhere access-controlled and deleted when the ticket closes. Run it past whoever owns data protection first.

A short checklist

  • One factory per entity, with overrides, and tests that assert only on what they set.
  • seed plus a fixed reference date plus a pinned version, or it isn't reproducible.
  • Reserved domains (example.com, .test) for every generated email.
  • Skewed distributions on purpose: a few heavy users, long strings, empty optional fields.
  • Volume from generate_series or a recursive CTE, not a 50 MB fixture file.
  • Treat any production-derived data as personal data until proven anonymous.

For wiring factories into a suite, our guides to choosing a test runner and testing React components with Vitest cover where fixtures and setup files belong.

AE

Written by AIDToolStack Editorial

Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.

Sources

  1. github.com/faker-js/faker/releases
  2. pypi.org/project/Faker/
  3. fakerjs.dev/guide/localization.html
  4. fakerjs.dev/api/internet.html
  5. www.rfc-editor.org/rfc/rfc2606.html
  6. fakerjs.dev/api/helpers.html
  7. fakerjs.dev/guide/usage.html
  8. faker.readthedocs.io/en/master/
  9. fakerjs.dev/guide/unique.html
  10. www.postgresql.org/docs/18/functions-srf.html
  11. eur-lex.europa.eu/legal-content/EN/TXT/HTML/?uri=CELEX:32016R0679
  12. www.edpb.europa.eu/our-work-tools/documents/public-consultations/2025/guidelines-012025-pseudonymisation_en
  13. www.npmjs.com/package/@faker-js/faker
  14. fakerjs.dev/api/date.html
  15. fakerjs.dev/api/string.html
  16. www.postgresql.org/docs/18/functions-datetime.html

Related Posts

Explore on AIDToolStack

Discover tools and servers featured in our directory.

MCP Servers

Trigger.dev Jobs MCP ServerManage Trigger.dev background jobs from your AI coding assistant. Monitor job runs, trigger tasks manually, inspect execution logs, manage schedules, and debug failed runs. The server provides operational visibility into your background job infrastructure — see which tasks are running, queued, or failed, and take action. Your AI can help diagnose job failures from execution logs, retry failed tasks, and optimize concurrency configurations for better throughput.Tailscale Network MCP ServerManage your Tailscale mesh VPN network from your AI coding assistant. View connected devices, manage ACLs, configure exit nodes, check device status, and manage DNS settings. The server provides visibility into your Tailscale network — see which machines are online, troubleshoot connectivity issues, manage network access policies, and configure routes. Useful for developers managing distributed infrastructure where Tailscale provides secure networking between services.Portainer Docker MCP ServerManage Docker environments through Portainer's API from your AI coding assistant. Control containers, images, networks, and volumes across multiple Docker hosts and Kubernetes clusters. The server provides tools for container lifecycle management, image pulling and building, stack deployment, and resource monitoring. Portainer's multi-environment management makes this server particularly valuable for teams managing containers across development, staging, and production environments.

Reviews

Sign in to leave a review.

No reviews yet. Be the first!

Comments

Sign in to leave a comment.

No comments yet. Be the first!

Sponsor Our Newsletter

Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.

Growing subscriber baseHigh open rates

All sponsored content is clearly labeled per our editorial policy.