Managing test data at each level of the test pyramid without production data: builders and object mothers for unit tests, unique data and Respawn resets for integration tests, seeded synthetic data (Bogus) for end-to-end environments, edge cases, versioned seed scripts, and Australian privacy obligations.
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.
"I treat test data as code, and the strategy changes with the level. In unit tests I use the builder pattern:
new OrderBuilder().WithTotal(0).Build(). The builder fills every other field with valid defaults, so the test shows the one thing that matters, and a new required property is fixed in one place instead of two hundred tests. For lots of varied input, AutoFixture or Bogus can fill the rest.In integration tests the rule is that each test owns its data. It inserts what it needs with unique keys, like a new Guid or a unique email, and only asserts on those rows. Between tests I reset with Respawn, which deletes rows in foreign-key order but keeps the schema and reference data. That isolation is what lets tests run in parallel and in any order. In end-to-end and UAT environments I seed synthetic data from a versioned seeder. Bogus with a fixed seed gives realistic names, addresses and amounts, and the same seed always gives the same data, so a failure reproduces. Edge cases go in deliberately: a customer called Zoë O'Brien-Nguyễn, a 0-dollar order, an order placed at 2:30 am on the night daylight saving starts in Sydney.
The mistake I see is 'just restore last night's production backup into test'. That copies real people's personal information into an environment with weaker access controls. Under the Privacy Act, APP 11 still requires reasonable steps to protect it, and a leak from a test database can be a notifiable data breach just like one from production. If the business really needs production-like volumes, the data goes through an approved, irreversible masking pipeline first. Real people stay in production."
| Level | Technique | Why |
|---|---|---|
| Unit | Builders, object mothers, AutoFixture or Bogus for filler | Readable tests; one place to change when the model changes |
| Integration | Unique keys per test + Respawn reset; reference data from migrations | Isolation, parallel runs, no order dependence |
| End-to-end / UAT | Seeder (Bogus with a fixed seed), versioned in git, run by the pipeline | Realistic, repeatable, no PII |
| Performance | Generated volume that matches production shape (row counts, skew, sizes) | Plans and indexes behave as in production |
| Category | Examples |
|---|---|
| Text | Unicode and accented names, apostrophes, 1-character and 200-character values, right-to-left text |
| Numbers | 0, negative, the maximum decimal(18,2), GST rounding (x.xx5) |
| Time | Daylight-saving changes in Australia/Sydney, UTC midnight against local midnight, leap day |
| Nulls and optionals | Missing middle name, no phone number |
A team that replaced a nightly masked production restore (about 40 GB, 2 hours) with a seeded synthetic environment can rebuild UAT in about 10 minutes from a versioned seeder. It also takes the test environment out of scope for data-breach risk assessments.
Checks whether the candidate has a deliberate test data strategy per level, keeps tests isolated, and treats privacy as a hard constraint.
Green flags
Red flags
Most flaky and unreadable tests come from data, not logic. Three patterns cause most of it:
Unit Integration End-to-end / UAT
builders → test-owned rows + reset → versioned synthetic seed
(in memory) (Testcontainers SQL) (deployed environment)
no production data at any level ──▶ privacy by design
A builder holds valid defaults for every field and exposes WithX methods. The test calls only the ones that matter. Builders absorb model changes: a new required property gets a default in one place. An object mother (Customers.Gold()) names common shapes. Use it sparingly, because it hides details again.
en_AU), and UseSeed(n) makes generation deterministic, so a failure on CI reproduces locally.Both are actively used in current .NET projects. The choice is about realism (Bogus) versus anonymity (AutoFixture).
Unique keys let tests run in parallel on one database. A reset between tests (Respawn, or a database per class) is needed when tests count rows or need empty tables. Reference data such as currencies, states and postcodes belongs in migrations, and Respawn's TablesToIgnore keeps it.
Personal information in a test environment is still personal information. Australian Privacy Principle 11 requires reasonable steps to protect it, and APP 6 limits using it for a purpose other than the one it was collected for. Using it for testing is hard to justify. A breach of a test database that is likely to cause serious harm is notifiable under the NDB scheme. Masking must be irreversible and must cover quasi-identifiers (date of birth plus postcode can re-identify someone). Synthesis avoids the problem entirely.
OrderBuilder with valid defaults and refactor three tests to use it. Then add a required property and see how many places change.en_AU customers with Bogus and UseSeed(42), and confirm two runs produce identical data.FakeTimeProvider.A builder for unit tests and a deterministic Bogus seeder for integration or UAT data (xUnit v3, Bogus).
#nullable enable
using Bogus;
using Xunit;
namespace Orders.Tests;
// ----- Code under test -----
public sealed record Customer(Guid Id, string Name, string Email, string Postcode);
public sealed record Order(Guid Id, Customer Customer, decimal Total, DateTimeOffset PlacedAt);
public static class FreightRules
{
// Free freight for orders of $100 or more.
public static decimal FreightFor(Order order) => order.Total >= 100m ? 0m : 9.95m;
}
// ----- Builder: valid defaults, tests override only what matters -----
public sealed class OrderBuilder
{
private decimal _total = 50m;
private Customer _customer = new(Guid.NewGuid(), "Test Customer", $"{Guid.NewGuid():N}@example.test", "2000");
private DateTimeOffset _placedAt = new(2026, 11, 21, 9, 0, 0, TimeSpan.FromHours(11));
public OrderBuilder WithTotal(decimal total) { _total = total; return this; }
public OrderBuilder WithCustomer(Customer customer) { _customer = customer; return this; }
public OrderBuilder PlacedAt(DateTimeOffset at) { _placedAt = at; return this; }
public Order Build() => new(Guid.NewGuid(), _customer, _total, _placedAt);
}
// ----- Synthetic data: realistic, deterministic, no real people -----
public static class SyntheticCustomers
{
public static List<Customer> Generate(int count, int seed = 42) =>
new Faker<Customer>("en_AU")
.UseSeed(seed) // same seed → same data, so failures reproduce
.CustomInstantiator(f => new Customer(
f.Random.Guid(),
f.Name.FullName(),
f.Internet.Email(provider: "example.test"), // reserved domain: never a real inbox
f.Address.ZipCode("####")))
.Generate(count);
}
public sealed class FreightRulesTests
{
[Theory]
[InlineData(99.99, 9.95)]
[InlineData(100.00, 0)] // boundary on purpose
[InlineData(0, 9.95)] // edge case: free-item order
public void Freight_depends_on_total(decimal total, decimal expected)
{
var order = new OrderBuilder().WithTotal(total).Build(); // only the field that matters
Assert.Equal(expected, FreightRules.FreightFor(order));
}
[Fact]
public void Unicode_names_are_preserved()
{
var customer = new Customer(Guid.NewGuid(), "Zoë O'Brien-Nguyễn", "[email protected]", "3000");
var order = new OrderBuilder().WithCustomer(customer).Build();
Assert.Equal("Zoë O'Brien-Nguyễn", order.Customer.Name);
}
[Fact]
public void Synthetic_data_is_repeatable()
{
var first = SyntheticCustomers.Generate(100);
var second = SyntheticCustomers.Generate(100);
Assert.Equal(first, second); // records compare by value
}
}
UseSeed(n), and log the seed when it varies.example.test or example.com.The strategic question is who maintains the seed as the system grows. I keep seeders in the same repository as the schema, run them in CI against every migration, and fail the build if seeding breaks. Then test data evolves with the model instead of rotting. For UAT I give the business named, scripted personas ("Gold customer with an overdue invoice") instead of random rows, so testers can find the case they need. I'd also write an ADR that says no production data below production. It's much easier to defend in a privacy review than a masking process.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Builders | Unit and integration tests | A class per aggregate | Huge, flat DTOs where AutoFixture does it in one line |
| Bogus synthetic seed | UAT, demos, end-to-end, performance shape | Seeder maintenance; realism takes care | You need real statistical distributions (use synthesis tools) |
| Masked production copy | Data migrations, rare production-shape investigations | Approved pipeline, audits, still a privacy risk | Day-to-day testing |
| Production data | Never below production | Legal and breach exposure | Always |
Derive a factory from WebApplicationFactory<Program> and implement IAsyncLifetime. InitializeAsync starts an MsSqlContainer, and DisposeAsync disposes the container and then the factory. In ConfigureWebHost, point the app at the container with UseSetting("ConnectionStrings:Orders", ...). You can also swap the DbContext registration in ConfigureTestServices.
Run EF Core migrations once per fixture, so the tests use the real schema. Then reset rows before each test with Respawn, which deletes data in foreign-key order and keeps the schema.
Use it as an IClassFixture and every class gets its own database. For speed, share one container and give each class a unique database name. The trade-off is that real SQL Server catches what in-memory providers hide (constraints, transactions, SQL translation), at the price of Docker and a few seconds of start-up.
Last updated 23 Nov 2026.