📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you manage test data for a .NET system that handles personal information? Compare test data builders, seeding, masked production copies and synthetic data, and explain how the Privacy Act shapes what you are allowed to use.

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.

Mid-Level Theory Intermediate bogus privacy synthetic-data test-data test-data-builders testing

🎯 Key points

  • Test data builders with valid defaults: each test states only the values that matter
  • Bogus for realistic fakes, with UseSeed so failures are reproducible; en_AU locale for addresses and phone numbers
  • Each test creates its own data (unique keys) or resets with Respawn/transactions; no shared mutable seed rows
  • Reference data (countries, product types) seeded once by migrations or a fixture
  • Production copies of personal information in non-production environments are a Privacy Act (APP 11) and NDB risk
  • Masking is hard to do safely (re-identification via free text, rare combinations); prefer synthetic data generated from the schema
  • Load and performance tests need realistic volume and distribution, generated not copied

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 the en_AU locale, 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."


Three kinds of test data

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

Techniques compared

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

Privacy checklist for non-production data

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

Production example

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.

🔍 What the interviewer is checking

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

  • Distinguishes reference, scenario and volume data
  • Builders with valid defaults; seeded Bogus
  • Per-test data or Respawn for isolation and parallelism
  • Knows APP 11 and NDB apply to test copies; explains masking's re-identification risk

Red flags

  • "We just restore production into test"
  • Shared seed rows modified by tests
  • Random data with no seed and no way to reproduce failures

📚 Learn in depth

1. Why test data goes wrong

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.

2. Test data builders

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.

3. Bogus and determinism

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.

4. Database isolation strategies

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.

5. Privacy law and non-production data

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:

  • Free text (notes, addresses in comments) carries names and phone numbers no regex catches.
  • Quasi-identifiers: postcode + date of birth + gender identifies many people.
  • Consistency: deterministic masking (same input, same output) can be reversed with a dictionary attack on common names.

6. Synthetic data for volume

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.

Try it yourself

  1. Write a builder for an aggregate with five required fields; refactor three tests to use it and count the lines removed.
  2. Generate 1,000 customers with Bogus en_AU and a seed; run twice and diff the output.
  3. Run a test suite in random order (xUnit v3 supports a randomised test order via configuration; or run classes in parallel) and find tests that share data.
  4. Set up Respawn against a Testcontainers SQL Server, listing your reference tables in TablesToIgnore.
  5. Take a sample masked dataset and try to re-identify a record using postcode, birth year and a free-text field.

💻 Code

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);
    }
}

⚠ Common mistakes

  • Mistake: A shared seed customer that many tests read and some modify. Why it is wrong: results depend on test order and parallelism. Instead: each test creates its own scenario data; seed only reference data.
  • Mistake: Copying the production database into test or UAT "because it's realistic". Why it is wrong: it is still personal information under APP 11, and a leak is a notifiable data breach. Instead: generate synthetic data; use masked copies only after a privacy impact assessment.
  • Mistake: Trusting masking of name and email columns only. Why it is wrong: free text and quasi-identifiers (postcode, date of birth) re-identify people. Instead: drop or regenerate free text and coarsen quasi-identifiers, or go fully synthetic.
  • Mistake: Unseeded Bogus or AutoFixture data in assertions. Why it is wrong: a failure can't be reproduced. Instead: UseSeed(...), or log the seed when randomising deliberately.
  • Mistake: Constructing full object graphs inline in every test. Why it is wrong: the value that matters is buried and every new required field breaks hundreds of tests. Instead: builders with valid defaults.
  • Mistake: Hard-coding real-looking emails or phone numbers at real domains. Why it is wrong: test runs can email or SMS real people. Instead: reserved domains (example.test, example.com) and reserved number ranges.
  • Mistake: Load testing with 1,000 uniform rows. Why it is wrong: query plans and caches behave differently from production's skewed data. Instead: generate realistic volume and distribution.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about test data at different levels of the pyramid Why: Checks they can apply the strategy consistently from unit to end-to-end tests.
    How to answer

    Choose the data strategy per test level:

    • Unit tests: test data builders with valid defaults, so each test states only the field it cares about.
    • Integration tests: every test creates its own rows with unique keys, and the database is reset with Respawn. No test relies on another test's data.
    • End-to-end and UAT: synthetic data seeded from code, for example Bogus with a fixed seed so runs repeat, and versioned in git.

    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.

  2. When: Candidate mentions Respawn or resetting the database Why: Checks they understand database reset strategies and their trade-offs.
    How to answer

    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.

  3. When: Candidate says production data should not be copied to test Why: Checks they can balance the privacy position against a real support need.
    How to answer

    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.

🛠 Real-world problems: how you handle them

UAT refreshed from production gave contractors access to customer records
Situation
A [retail] platform refreshed its UAT Azure SQL database from a production backup every month so testers had 'real' data. UAT was accessible to [40] staff and contractors, and had no auditing.
Signals
A security review flagged UAT as holding [n] customer records including addresses and order history; a developer had exported a UAT table to a spreadsheet to debug a report; integration tests also broke after each refresh because they depended on specific customer ids.
Investigation
I inventoried non-production stores and their data sources, checked who had access (Entra ID group membership), and listed the tests that depended on refreshed ids. I tested the masking script the team proposed and showed free-text delivery notes still contained names and mobile numbers.
Resolution
Immediate: restricted UAT access to a small group, enabled auditing and deleted the exported spreadsheet. Fix: built a seeded Bogus generator (`en_AU`, realistic postcode and order-size distributions) run from the pipeline to rebuild UAT in 12 minutes, rewrote the id-dependent tests to create their own data with builders, and stopped the production refresh.
Prevention
Added a policy and pipeline check that non-production databases are only created from the generator; recorded the decision in an ADR; added non-production stores to the privacy data inventory review each quarter.

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.

More in Senior Testing Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me