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

📚 Interview question

How do you manage test data across unit, integration and end-to-end tests without using production data?

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.

Intermediate Theory Intermediate bogus integration-testing privacy test-data test-data-builders testing

🎯 Key points

  • Unit tests: test data builders (WithX methods, valid defaults) so each test states only what matters
  • Integration tests: each test creates its own rows with unique keys; reset with Respawn; no shared mutable seed
  • End-to-end and UAT: seeded synthetic data from code (Bogus with a fixed seed for repeatability), versioned in git
  • Edge cases on purpose: Unicode names, long strings, boundary amounts, time zones (Australia/Sydney DST), nulls
  • Never copy production PII into lower environments: Privacy Act 1988 APP 11 and the Notifiable Data Breaches scheme apply to test copies too
  • If realistic volumes are needed: irreversible masking or synthesis through an approved, audited pipeline
  • Reference data (currencies, postcodes) seeded with migrations and left out of resets

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Strategy by test level

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

Edge cases worth seeding

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate has a deliberate test data strategy per level, keeps tests isolated, and treats privacy as a hard constraint.

Green flags

  • Builders for unit tests, test-owned data and resets for integration tests.
  • Deterministic synthetic data (a fixed seed) and versioned seeders.
  • Deliberate edge cases (Unicode, boundaries, daylight saving).
  • Knows production PII in test environments is a privacy and breach risk (APP 11, NDB).

Red flags

  • "We just restore production into test."
  • Shared seeded data that tests change.
  • Random data with no way to reproduce failures.

📚 Learn in depth

1. Why test data goes wrong

Most flaky and unreadable tests come from data, not logic. Three patterns cause most of it:

  • Shared mutable fixtures: one seeded customer that every test changes.
  • Mystery guests: data inserted somewhere far from the test, so the reader can't see why it passes.
  • Production copies: real data that is unpredictable, huge and legally sensitive.
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

2. Test data builders

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.

3. Generators: Bogus and AutoFixture

  • Bogus (MIT) generates realistic values: names, addresses, company names, amounts. It supports locales (en_AU), and UseSeed(n) makes generation deterministic, so a failure on CI reproduces locally.
  • AutoFixture (MIT) fills object graphs with anonymous values. It's good for "I don't care about these fields" in unit tests, less good for realistic data.

Both are actively used in current .NET projects. The choice is about realism (Bogus) versus anonymity (AutoFixture).

4. Isolation in integration tests

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.

5. The privacy side

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.

Try it yourself

  1. Write an OrderBuilder with valid defaults and refactor three tests to use it. Then add a required property and see how many places change.
  2. Generate 1,000 en_AU customers with Bogus and UseSeed(42), and confirm two runs produce identical data.
  3. Seed a Unicode name and a 200-character address, and run your API's create and search endpoints against them.
  4. Write a test that places an order at 2:30 am on the October daylight-saving day in Australia/Sydney using FakeTimeProvider.
  5. List every column in your schema that holds personal information and check that the seeder never needs real values for them.

💻 Code

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

⚠ Common mistakes

  • Mistake: Restoring a production backup into test or UAT. Why it is wrong: It copies real personal information into weaker environments, with APP 11 and notifiable breach exposure. Instead: Seed synthetic data, or use an approved, irreversible masking pipeline.
  • Mistake: One shared seeded customer that many tests change. Why it is wrong: Tests depend on order and fail in parallel. Instead: Each test creates its own rows with unique keys, and you reset between tests.
  • Mistake: Building full objects inline in every test. Why it is wrong: The important value is buried, and every model change breaks many tests. Instead: Use builders with valid defaults.
  • Mistake: Random data without a seed. Why it is wrong: A failure on CI can't be reproduced. Instead: Use Bogus UseSeed(n), and log the seed when it varies.
  • Mistake: Only "happy" data (ASCII names, round amounts, UTC times). Why it is wrong: Production bugs live in Unicode, boundaries and daylight-saving changes. Instead: Seed edge cases on purpose.
  • Mistake: Masking only obvious columns such as name and email. Why it is wrong: Date of birth plus postcode and free-text notes can still identify people. Instead: Classify every column, including free text, or don't use production data at all.
  • Mistake: Using the EF Core in-memory provider to avoid seeding a real database. Why it is wrong: It doesn't enforce constraints, so invalid test data passes. Instead: Seed a real SQL Server in Testcontainers.
  • Mistake: Using real email domains in generated data. Why it is wrong: A test run can email real people. Instead: Use reserved domains such as example.test or example.com.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Respawn or resetting a real database between tests. Why: Checks they can wire a real SQL Server into API tests.
    How to answer

    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.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me