Test data strategy for systems with personal information: object mothers and test data builders, Bogus with fixed seeds, per-test seeding and reset, masked production copies versus synthetic data, and Australian Privacy Act and Notifiable Data Breaches implications.
I keep test data owned by the test. In code, test data builders give every object valid defaults, so a test only states what matters (AnOrder().WithStatus(Cancelled)). For realistic values I use Bogus with a fixed seed so a failure reproduces exactly. In integration tests each test inserts its own rows with unique keys, or the database is reset with Respawn; only stable reference data is seeded once. For staging and load tests I generate synthetic data from the schema rather than copying production. Under the Privacy Act 1988 (APP 11), a production copy in a test environment is still personal information you must protect, and a leak from it is a notifiable data breach. Masking sounds safe but free text and rare combinations re-identify people. The trade-off: building generators takes effort up front, but removes a whole class of privacy risk.
"I separate three kinds of test data. Reference data, like countries or product categories, is the same for every test, so I seed it once through migrations or a fixture. Scenario data is what a test is actually about, so the test creates it itself. And volume data is what load and performance tests need. Mixing them up is where most pain comes from: a shared 'test customer 1' that ten tests depend on and one test modifies.
For scenario data in code I use test data builders. A builder has valid defaults for everything, and the test overrides only what it is about, so
AnOrder().WithStatus(Cancelled).Build()says exactly what matters. When I need realistic names, addresses or ABNs I layer Bogus underneath with a fixed seed, using theen_AUlocale, so the data looks like ours but a failing test reproduces bit for bit. In database tests each test uses unique keys, or I reset with Respawn between tests, so tests can run in parallel and in any order.The bigger question is where non-production data comes from. Copying production into test is tempting because it is 'real', but under the Privacy Act it is still personal information: APP 11 requires reasonable steps to protect it, and if a test database leaks, it is an eligible data breach you may have to notify to the OAIC and the people affected. Test environments usually have weaker access controls, more people and more exports, so the risk is higher, not lower. Masking helps less than people think: free-text notes, rare combinations like postcode plus date of birth, and joins back to other systems re-identify people. So I prefer synthetic data generated from the schema with realistic distributions, and use masked copies only with a privacy impact assessment and sign-off. Tests should prove the code works, not hold a second copy of your customers."
| Kind | Example | Where it comes from | Lifetime |
|---|---|---|---|
| Reference | States, product types, tax codes | Migrations / one-off fixture seed | Whole run |
| Scenario | The cancelled order this test checks | The test, via builders | One test |
| Volume | 2 million orders for a load test | Synthetic generator | Environment |
| Technique | Good at | Weakness |
|---|---|---|
Object mother (TestOrders.Cancelled()) |
Named, reusable cases | Grows into hundreds of variants |
| Test data builder | Valid defaults, intention-revealing overrides | Some code to write per aggregate |
| Bogus (MIT licence) | Realistic values, locales, volume | Random unless seeded; can hide the value that matters |
| AutoFixture | Fills unknown parameters automatically | Values are unrealistic; obscures intent |
| Per-test inserts + Respawn | Isolation, parallelism | Needs a real database per test run |
| Masked production copy | Real distributions and edge cases | Re-identification risk; privacy obligations remain |
| Synthetic from schema | No personal information at all | Effort to model realistic distributions |
| Question | If yes |
|---|---|
| Does any non-production store hold real personal information? | Treat it as production for access, encryption and logging; record it in the data inventory |
| Is it sensitive information (health, financial hardship)? | Don't copy it; synthetic only |
| Could masked data be re-identified by combination or free text? | Drop or generate those fields |
| Do developers export it locally? | Stop; local copies are uncontrolled |
A team refreshed UAT from a production backup monthly, giving [40] contractors read access to [n] customer records. Replacing the refresh with a Bogus-based generator (seeded, en_AU, realistic order and postcode distributions) took about [two sprints]; UAT data was rebuilt in 12 minutes from a pipeline, and the security review removed UAT from the list of systems holding personal information.
Checks whether the candidate can design test data that keeps tests isolated and readable, and understands the privacy obligations of using real data outside production.
Green flags
Red flags
Most brittle suites share data. One test changes Customer 1's address, another expects the old one, and the failure depends on order. Or a test relies on "there are exactly three active products" and breaks when someone adds a fourth to the seed. The cure is ownership: each test creates what it reads.
A builder is a small fluent class with valid defaults:
AnOrder() -> customer: default valid customer
.WithStatus(Cancelled) -> lines: one default line
.WithLine(sku, qty) -> status: overridden
.Build() -> Order (passes domain invariants)
Because defaults are valid, a test that only cares about status doesn't need to know how to construct a valid address. When the domain adds a required field, you change one builder, not 200 tests. Records with with expressions are a lightweight alternative for simple DTOs.
Bogus generates realistic values from locale datasets. Randomness is good for finding edge cases you didn't think of, but bad for reproducibility. Two techniques:
new Faker<T>().UseSeed(1234) makes a specific faker deterministic.Randomizer.Seed = new Random(1234) sets it globally (avoid with parallel tests: shared state).Log the seed when you use a random one, so a failure in CI can be replayed locally. That is the same idea property-based testing tools like FsCheck use.
Strategy Isolation Speed Parallel-safe
--------------------- ---------- --------- -------------
Transaction rollback High Fast Yes (per conn)
Respawn reset High Fast-ish Per database
Unique keys per test Medium Fastest Yes
Database per class Highest Slowest Yes
Transaction rollback breaks when the code under test opens its own transaction or uses a second connection. Respawn deletes from tables in foreign-key order (skipping reference tables you list) and is the usual choice with Testcontainers.
Under the Privacy Act 1988, APP 11 requires entities to take reasonable steps to protect personal information from misuse, interference, loss and unauthorised access, and to destroy or de-identify it when no longer needed. Nothing in the Act exempts test environments. The Notifiable Data Breaches scheme (Part IIIC) applies when unauthorised access is likely to result in serious harm; a leaked UAT database is treated the same as a leaked production one. The OAIC's guidance on de-identification stresses that data is only de-identified if the risk of re-identification is very low in the context it is released into, which is hard to guarantee when developers can join tables freely.
Masking pitfalls:
A generator that knows the schema and realistic distributions (orders per customer follow a long tail; 80% of traffic to 20% of products; postcodes weighted by population) produces data that exercises indexes and query plans like production without containing anyone. Combine Bogus for values with your own distribution logic, and bulk-insert with SqlBulkCopy or EF Core ExecuteUpdate-style batching.
en_AU and a seed; run twice and diff the output.TablesToIgnore.A test data builder backed by a seeded Bogus faker, used in an xUnit test of a simple domain rule.
// Shop/Orders.cs
namespace Shop;
public enum OrderStatus { Placed, Shipped, Cancelled }
public sealed record Address(string Street, string Suburb, string State, string Postcode);
public sealed record Customer(Guid Id, string Name, string Email, Address Address);
public sealed record Order(Guid Id, Customer Customer, OrderStatus Status, decimal Total)
{
public bool CanBeRefunded => Status is OrderStatus.Shipped or OrderStatus.Placed && Total > 0;
}
// Shop.Tests/Builders/OrderBuilder.cs
using Bogus;
using Shop;
namespace Shop.Tests.Builders;
public sealed class OrderBuilder
{
// Seeded: the same 'random' customer every run, so failures reproduce.
private static readonly Faker<Customer> Customers = new Faker<Customer>("en_AU")
.UseSeed(20261121)
.CustomInstantiator(f => new Customer(
f.Random.Guid(),
f.Name.FullName(),
f.Internet.Email(provider: "example.test"), // never a real domain
new Address(f.Address.StreetAddress(), f.Address.City(), f.Address.StateAbbr(), f.Address.ZipCode("####"))));
private OrderStatus _status = OrderStatus.Placed;
private decimal _total = 120.00m;
private Customer? _customer;
public static OrderBuilder AnOrder() => new();
public OrderBuilder WithStatus(OrderStatus status) { _status = status; return this; }
public OrderBuilder WithTotal(decimal total) { _total = total; return this; }
public OrderBuilder For(Customer customer) { _customer = customer; return this; }
public Order Build() => new(Guid.NewGuid(), _customer ?? Customers.Generate(), _status, _total);
}
// Shop.Tests/RefundRuleTests.cs
using Shop;
using Xunit;
using static Shop.Tests.Builders.OrderBuilder;
namespace Shop.Tests;
public sealed class RefundRuleTests
{
[Fact]
public void CancelledOrder_CannotBeRefunded()
{
// Only the value under test is stated; everything else is a valid default.
var order = AnOrder().WithStatus(OrderStatus.Cancelled).Build();
Assert.False(order.CanBeRefunded);
}
[Fact]
public void ZeroValueOrder_CannotBeRefunded()
{
var order = AnOrder().WithTotal(0m).Build();
Assert.False(order.CanBeRefunded);
}
}
UseSeed(...), or log the seed when randomising deliberately.example.test, example.com) and reserved number ranges.Test data is a design problem and a compliance problem at the same time. On the design side, builders and per-test data make suites order-independent and parallel, which is what keeps them fast as they grow. On the compliance side, the senior position is that non-production environments should hold no real personal information by default, because they have more people, weaker controls and more exports than production. Arguing "we need real data to find real bugs" is usually solved better by capturing the specific shape of a production bug as a synthetic case.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Builders + per-test data | Unit and integration tests | Builder code per aggregate | Volume tests |
| Seeded Bogus generator | Staging, demos, load tests | Modelling distributions | Asserting exact business values |
| Masked production copy | Rare: data migration rehearsals with PIA and sign-off | Ongoing privacy obligations, re-identification risk | Routine dev/test |
| Production read replica access | Never for tests | High breach risk | Always |
I'd measure progress with two numbers: how many non-production stores contain real personal information (target zero), and the flake rate attributable to shared data.
Choose the data strategy per test level:
Build edge cases in on purpose: Unicode names, boundary amounts, Australian daylight-saving changes. Never copy production PII into lower environments. Under the Privacy Act 1988 (APP 11), a test copy is still personal information you must protect, and a leak can be a notifiable data breach. The trade-off is that synthetic data takes effort to make realistic, but it removes a whole class of privacy risk.
The EF Core in-memory provider is fast but not a relational database: it ignores constraints, transactions and SQL translation, so tests pass that would fail in production. Microsoft now advises against it for testing.
SQLite in-memory is relational and quick, but it is a different dialect: column types, schemas, collation and some LINQ translations differ from SQL Server.
For real confidence I run SQL Server in a container with Testcontainers, apply the real migrations once, and reset data between tests with Respawn (delete in foreign-key order) or a rolled-back transaction.
The trade-off: a few seconds of container start-up per run in exchange for testing the same engine you ship on.
Copying customer records into UAT is a use of personal information under the Privacy Act 1988: APP 6 limits use to the purpose it was collected for, APP 11 requires reasonable security, and a leak from UAT is still a notifiable data breach. So first reproduce the shape of the data, not the data: work out what triggers the bug from logs, the customer's report or a query run in production by someone authorised, recreate it synthetically in UAT, and keep it as a regression test. If that genuinely isn't possible, extract only the minimum records with documented approval (privacy officer or data owner), mask everything not needed for the bug, put them in a restricted store where only named people in a defined role can read them, log who accessed what and when, set a deletion date and delete them, and record the decision against APP 11.
How to tell it (STAR)
**S:** At [company], our UAT database was refreshed monthly from production and [40] people could read real customer records. **T:** After a security review flagged it, I was asked to remove real personal information from non-production without slowing testing. **A:** I showed the proposed masking missed names and phone numbers in free-text notes, so instead I built a seeded synthetic data generator with realistic distributions, rebuilt UAT from the pipeline, and moved our brittle tests to builders that create their own data. **R:** UAT rebuilds took 12 minutes, [n] tests stopped breaking after refreshes, and UAT was removed from our list of systems holding personal information.
Last updated 23 Nov 2026.