Covers AutoFixture (Create, Build/With, AutoData, Frozen, AutoNSubstitute), hand-written test data builders and Object Mothers, Bogus for realistic synthetic data, and the trade-off between anonymous values and readable, intention-revealing tests.
Both solve the same problem: tests drowning in setup for objects whose details don't matter.
fixture.Create<Order>() fills every property, Build<Order>().With(o => o.Status, Paid).Create() pins what matters, and [AutoData] injects generated parameters. With AutoNSubstitute and [Frozen] it can build the class under test with substitutes too.new OrderBuilder().WithStatus(Paid).Build()) with valid defaults, so each test states only what it is about.en_AU locale) for demos, seeding and load tests.The trade-off: generated data cuts noise and survives constructor changes, but hides intent when the value that drives the result is invisible. Make the values that matter explicit.
"Most test setup is noise: to test that a paid order can be refunded, I need an
Orderwith a customer, lines, an address and so on, and none of that matters except the status. If every test builds it by hand, adding one required property breaks 200 tests, and readers can't see which value actually matters.AutoFixture attacks that by generating anonymous values.
fixture.Create<Order>()uses reflection to pick the greediest constructor and fill every property with unique values: strings likeName7f3a..., incrementing numbers, nested objects. I override only what matters:fixture.Build<Order>().With(o => o.Status, OrderStatus.Paid).Create(). WithAutoNSubstitutecustomisation and[Frozen]on a parameter, it'll even construct my service with substitutes and hand me the same substitute to configure. It's very effective at keeping tests stable when constructors change.The other approach is a hand-written test data builder: an
OrderBuilderwith sensible valid defaults and methods likeWithStatusandWithLine. It's more code to maintain, but it reads like the domain and it always produces a valid object, which AutoFixture doesn't guarantee when your invariants live in constructors or validators. I use Bogus when I want realistic data, like Australian names and postcodes for a demo environment or seeding a load test, always with a fixed seed so failures are reproducible.The mistake I see is AutoFixture used everywhere so that the test passes or fails based on a random value nobody can see. My rule is: if a value influences the assertion, it's written in the test. Generated data is for the things that don't matter."
| Approach | What it is | Strength | Weakness |
|---|---|---|---|
Inline new |
Construct everything in the test | Fully explicit | Noise; breaks on every constructor change |
| Object Mother | TestOrders.PaidOrder() static factory |
Short, named scenarios | Grows into dozens of near-duplicates |
| Test data builder | Fluent builder with valid defaults | Intention-revealing, valid by default | Code to maintain per aggregate |
| AutoFixture | Reflection-based anonymous values | Near-zero setup, refactor-proof | Hides intent; can create invalid domain objects |
| Bogus | Rule-based realistic fake data | Realistic, locale-aware, seedable | Not designed for "anonymous" values |
| Situation | Choice |
|---|---|
| Domain logic with invariants | Test data builder |
| Mapping or serialisation tests over big DTOs | AutoFixture |
| Services with many constructor dependencies | AutoFixture + AutoNSubstitute, or rethink the design |
| Demo, UAT or load-test seed data | Bogus with a fixed seed |
| A handful of simple value objects | Just new them |
Adding a required CountryCode to Customer broke 340 tests in a billing service that constructed customers inline. The team introduced a CustomerBuilder with "AU" as the default; the next required property (TaxResidency) was a one-line change in the builder and broke zero tests.
Checks whether the candidate can keep test setup small without hiding intent, and handles test data responsibly.
Green flags
Red flags
fixture.Create<Order>()
|
|-- find a builder for Order (customisations first)
|-- choose the constructor with the most parameters (by default)
|-- recursively Create each parameter type
|-- assign writable properties with generated values
v
Order { Id = 42, Customer = { Name = "Name1c2d..." }, Lines = [3 items] }
The engine is a chain of specimen builders. Each builder either produces a value for a request (a type, a parameter, a property) or passes. Customisations insert builders at the front, which is how Build<T>().With(...), fixture.Customize<T>(...) and Register work. Strings get a prefix plus a GUID, numbers are unique and increasing, collections default to three items.
[AutoData] creates every test parameter with a fresh fixture; [InlineAutoData(1, 2)] mixes fixed and generated values. Glue packages are per framework and version (for example AutoFixture.Xunit2 for xUnit v2), so check which package supports the framework version you use.AutoNSubstituteCustomization (or AutoMoq) makes the fixture return substitutes for interfaces.[Frozen] on a parameter registers that instance so every later request for the type returns the same object, which is how you get the substitute injected into the class under test.A builder holds defaults in fields and returns this from each With... method; Build() calls the real constructor, so domain invariants run. Records with with expressions give a lightweight variant: a static valid default and Default with { Status = Paid }.
Bogus (MIT) uses rules: new Faker<Customer>("en_AU").RuleFor(c => c.Name, f => f.Name.FullName()). Randomizer.Seed = new Random(1234) or UseSeed(1234) makes output deterministic. It generates believable data for demo environments and load tests without touching production data, which matters under the Privacy Act 1988: production personal information copied into a test environment is still personal information and in scope for the Notifiable Data Breaches scheme.
Anonymous values are unique per run, so a test that passes by coincidence (for example, an int that happens to be positive) can fail later. Make domain rules explicit in builders, and log or assert on the inputs that matter.
fixture.Create<T>() three times; look at the values.[AutoData] and [Frozen] IRepository repo using AutoNSubstitute, and configure the frozen substitute.OrderBuilder and refactor three tests to use it; count lines before and after.new, the builder and AutoFixture.en_AU customers with Bogus using a fixed seed and check the output is identical across runs.The same refund rule tested with a hand-written builder and with AutoFixture, plus Bogus for seed data:
// Order.cs (code under test)
namespace Billing;
public enum OrderStatus { New, Paid, Shipped, Refunded }
public sealed record Customer(string Name, string Email, string CountryCode);
public sealed record Order(int Id, Customer Customer, decimal Total, OrderStatus Status, DateOnly PlacedOn)
{
public bool CanRefund(DateOnly today) =>
Status is OrderStatus.Paid or OrderStatus.Shipped && today.DayNumber - PlacedOn.DayNumber <= 30;
}
// OrderBuilder.cs + OrderTests.cs (xunit.v3, AutoFixture, Bogus)
using AutoFixture;
using Billing;
using Bogus;
using Xunit;
namespace Billing.Tests;
// Valid defaults; tests set only what they are about.
public sealed class OrderBuilder
{
private OrderStatus _status = OrderStatus.Paid;
private DateOnly _placedOn = new(2026, 11, 1);
public OrderBuilder WithStatus(OrderStatus status) { _status = status; return this; }
public OrderBuilder PlacedOn(DateOnly date) { _placedOn = date; return this; }
public Order Build() =>
new(1, new Customer("Test Customer", "[email protected]", "AU"), 100m, _status, _placedOn);
}
public sealed class OrderTests
{
private static readonly DateOnly Today = new(2026, 11, 21);
[Theory]
[InlineData(OrderStatus.Paid, true)]
[InlineData(OrderStatus.Shipped, true)]
[InlineData(OrderStatus.New, false)]
[InlineData(OrderStatus.Refunded, false)]
public void Refund_depends_on_status(OrderStatus status, bool expected) =>
// The value that drives the result is visible in the test.
Assert.Equal(expected, new OrderBuilder().WithStatus(status).Build().CanRefund(Today));
[Fact]
public void Refund_window_closes_after_30_days() =>
Assert.False(new OrderBuilder().PlacedOn(Today.AddDays(-31)).Build().CanRefund(Today));
[Fact]
public void AutoFixture_version_pins_only_what_matters()
{
var fixture = new Fixture();
fixture.Register(() => Today.AddDays(-5)); // DateOnly values: recent
var order = fixture.Build<Order>()
.With(o => o.Status, OrderStatus.Paid)
.Create(); // Id, Customer and Total are anonymous: they don't affect the rule
Assert.True(order.CanRefund(Today));
}
[Fact]
public void Bogus_generates_repeatable_synthetic_customers()
{
// Synthetic Australian data with a fixed seed: realistic, reproducible, no real PII.
var faker = new Faker<Customer>("en_AU")
.UseSeed(1234)
.CustomInstantiator(f => new Customer(f.Name.FullName(), f.Internet.Email(), "AU"));
var first = faker.Generate(3);
var again = new Faker<Customer>("en_AU").UseSeed(1234)
.CustomInstantiator(f => new Customer(f.Name.FullName(), f.Internet.Email(), "AU")).Generate(3);
Assert.Equal(first, again);
}
}
With(...) or a builder method.PaidOrderWithTwoLinesAndDiscount() style methods. Why it is wrong: It becomes a god class nobody can navigate. Instead: Switch to a builder with composable With... methods.UseSeed(...) and log the seed.Test data strategy is a readability decision first. I default to hand-written builders for domain aggregates because they keep tests honest about invariants and read like the domain, and use AutoFixture where the shape is big and the values irrelevant (mapping, serialisation, DTO plumbing). Bogus is for realistic environments and load tests, never for values a unit test asserts on. AutoFixture's development pace has slowed, so check its support for your test framework version before adopting it widely.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Test data builder | Aggregates with invariants, many tests | One class per aggregate | Trivial value objects |
| AutoFixture | Large DTOs, mapping tests, anonymous inputs | Learning curve, hidden values | When the reader needs to see the data |
| Bogus | Seeding, demos, load tests, synthetic PII-free data | Rules to write | Unit-test assertions |
Records + with |
Small immutable types | Almost none | Types with constructor validation you must call |
Measure the effect by counting how many tests break when a constructor gains a parameter; with builders it should be zero or one file.
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.
A mock library generates a runtime implementation of an interface or virtual members so a unit test can exercise the class under test in isolation from slow or non-deterministic dependencies: you control what each dependency returns and check the calls that matter.
var repo = Substitute.For<IOrderRepository>();, repo.GetAsync(42, Arg.Any<CancellationToken>()).Returns(order);, then await repo.Received(1).SaveAsync(Arg.Is<Order>(o => o.Status == Paid), Arg.Any<CancellationToken>());.new Mock<T>(), Setup(...).ReturnsAsync(...), Verify(..., Times.Once) and mock.Object; MockBehavior.Strict throws on any call that was not set up.In August 2023 Moq 4.20.0 bundled SponsorLink, an analyser that read the developer's git email and sent a hash to a sponsorship service; after a backlash it was removed in 4.20.2. The lesson is supply-chain hygiene. The trade-off with mocks: they isolate logic quickly, but too many verifications couple tests to implementation.
Last updated 23 Nov 2026.