Introduction
In the previous lesson, we tested exceptions, validation rules, and edge cases. As those tests grow, another concern becomes important: creating reliable, readable, and reusable test data. Creating data directly inside every test may seem simple at first. However, as the suite expands, setup code is duplicated, tests can start depending on state created by other tests, and the reason for a failure becomes harder to understand.
This lesson treats test data creation as a design concern. We will combine fixtures, builders, factories, and xUnit parameterized tests to keep tests independent, deterministic, and maintainable. The examples use product and order concepts from the order application.
1. Characteristics of good test data
Test data should do more than allow a test to run. It should make the purpose of the test visible and produce the same result whenever the test is repeated.
- Independent: Data created or changed by one test must not affect another test.
- Deterministic: Dates, random numbers, sequence values, and environment settings must not change the result unexpectedly.
- Minimal: Fields that are irrelevant to the behavior under test should not add noise.
- Readable: The business rule being verified should be easy to identify.
- Reusable: Common scenarios should be generated consistently instead of being rewritten in every test.
For example, if a test only verifies an order total, repeatedly writing every address field or a real database identifier is unnecessary.
2. Creating meaningful objects with a builder
A builder creates a complex object using valid defaults and allows a test to override only the fields that matter. Consider this simplified order model:
public sealed record OrderItem(Guid ProductId, int Quantity, decimal UnitPrice); public sealed class Order { public Guid Id { get; init; } public Guid CustomerId { get; init; } public DateTime CreatedAtUtc { get; init; } public List<OrderItem> Items { get; init; } = []; public decimal Total => Items.Sum(item => item.Quantity * item.UnitPrice); }
Instead of constructing Order manually in every test, create a builder:
public sealed class OrderBuilder { private Guid _id = Guid.Parse("11111111-1111-1111-1111-111111111111"); private Guid _customerId = Guid.Parse("22222222-2222-2222-2222-222222222222"); private DateTime _createdAtUtc = new(2026, 1, 15, 10, 0, 0, DateTimeKind.Utc); private readonly List<OrderItem> _items = []; public OrderBuilder WithId(Guid id) { _id = id; return this; } public OrderBuilder ForCustomer(Guid customerId) { _customerId = customerId; return this; } public OrderBuilder CreatedAt(DateTime createdAtUtc) { _createdAtUtc = createdAtUtc; return this; } public OrderBuilder WithItem(int quantity = 1, decimal unitPrice = 10m) { _items.Add(new OrderItem( Guid.Parse("33333333-3333-3333-3333-333333333333"), quantity, unitPrice)); return this; } public Order Build() { return new Order { Id = _id, CustomerId = _customerId, CreatedAtUtc = _createdAtUtc, Items = [.. _items] }; } }
The important part of the test is now easy to see:
[Fact] public void Total_ShouldMultiplyQuantityByUnitPrice() { var order = new OrderBuilder() .WithItem(quantity: 2, unitPrice: 25m) .Build(); order.Total.Should().Be(50m); }
A builder should produce a valid object by default. For invalid scenarios, add separate methods whose names express the intent. For example, WithoutItems or WithManyItems is usually clearer than assigning an empty collection directly inside every test.
3. Producing scenario-focused data with a factory
A builder is useful for configuring object fields. A factory gives a meaningful name to a complete business scenario. In an application with different payment states or order categories, factory methods can make tests more expressive.
public static class OrderFactory { public static Order PendingOrder(decimal unitPrice = 20m) { return new OrderBuilder() .WithItem(quantity: 1, unitPrice: unitPrice) .Build(); } public static Order BulkOrder() { return new OrderBuilder() .WithItem(quantity: 10, unitPrice: 5m) .Build(); } public static Order EmptyOrder() { return new OrderBuilder().Build(); } }
The test expresses the scenario without exposing every construction detail:
[Fact] public void BulkOrder_ShouldHaveExpectedTotal() { var order = OrderFactory.BulkOrder(); order.Total.Should().Be(50m); }
Builders and factories do not have to be alternatives. A factory can use a builder to provide common, named scenarios. Use the builder directly when a test needs to customize one or two specific properties.
4. Fixtures and object lifetime
xUnit creates a new instance of the test class for each test. Therefore, a constructor can hold simple reusable setup without sharing the same test-class instance between tests. When initialization is expensive, use IClassFixture<T>. xUnit creates one class fixture for the test class and disposes it after the tests complete.
public sealed class OrderFixture { public Guid CustomerId { get; } = Guid.Parse("22222222-2222-2222-2222-222222222222"); public Order CreateOrder(decimal price = 10m, int quantity = 1) { return new OrderBuilder() .ForCustomer(CustomerId) .WithItem(quantity, price) .Build(); } } public sealed class OrderTotalTests : IClassFixture<OrderFixture> { private readonly OrderFixture _fixture; public OrderTotalTests(OrderFixture fixture) { _fixture = fixture; } [Fact] public void Total_ShouldUseFixtureCustomer() { var order = _fixture.CreateOrder(price: 12m, quantity: 2); order.CustomerId.Should().Be(_fixture.CustomerId); order.Total.Should().Be(24m); } }
Be careful when a fixture contains a mutable shared list or database state. If one test adds a record, a later test may see a different starting state. Prefer fixtures that are read-only or create a new object for each call. When a shared test database is necessary, clean and seed it before each test or use an isolated database scope.
5. Verifying one behavior with parameterized tests
When the same behavior must be checked with multiple inputs, use Theory instead of creating many nearly identical Fact methods. For simple constants, InlineData is sufficient.
[Theory] [InlineData(1, 10, 10)] [InlineData(2, 10, 20)] [InlineData(3, 7.5, 22.5)] public void Total_ShouldBeCalculatedForDifferentQuantities( int quantity, decimal unitPrice, decimal expectedTotal) { var order = new OrderBuilder() .WithItem(quantity, unitPrice) .Build(); order.Total.Should().Be(expectedTotal); }
For more complex data, use MemberData or ClassData. A record gives the test case named fields:
public sealed record OrderTotalCase( int Quantity, decimal UnitPrice, decimal ExpectedTotal); public static class OrderTestCases { public static IEnumerable<OrderTotalCase> TotalCases => [ new(1, 15m, 15m), new(4, 12.5m, 50m), new(10, 3m, 30m) ]; } [Theory] [MemberData(nameof(OrderTestCases.TotalCases), MemberType = typeof(OrderTestCases))] public void Total_ShouldMatchCase(OrderTotalCase testCase) { var order = new OrderBuilder() .WithItem(testCase.Quantity, testCase.UnitPrice) .Build(); order.Total.Should().Be(testCase.ExpectedTotal); }
Each row in a parameterized test should be treated as an independent test case. The data should make it clear which input failed. Avoid putting every possible combination into one theory; use focused data sets that represent the same business rule.
6. Controlling time and randomness
A common source of flaky tests is direct dependence on the system clock. Code that uses DateTime.UtcNow can fail around midnight, because of time zones, or because of small timing differences. Hide clock access behind an abstraction:
public interface IClock { DateTime UtcNow { get; } } public sealed class FixedClock(DateTime utcNow) : IClock { public DateTime UtcNow { get; } = utcNow; }
The production application can use a real clock provider, while a test can inject a fixed value:
var clock = new FixedClock( new DateTime(2026, 1, 15, 12, 0, 0, DateTimeKind.Utc)); var createdAt = clock.UtcNow; createdAt.Should().Be(new DateTime( 2026, 1, 15, 12, 0, 0, DateTimeKind.Utc));
The same principle applies to random identifiers, GUIDs, and sequence numbers. If a test depends on randomness, inject a seeded generator or a provider controlled by the test. Converting randomness into an injectable dependency is safer than hiding it inside the method being tested.
7. Common mistakes
- Using global state: If tests mutate the same static collection, execution order can change the result.
- Using the real current time: Expectations built with DateTime.UtcNow change as time passes.
- Creating an oversized fixture: Dozens of objects that a test does not need hide the purpose of the test.
- Making the builder too intelligent: A builder should not reimplement the business rules being tested, or it may contain the same bug.
- Using meaningless parameters: Prefer names such as quantity and unitPrice over value1 and value2.
- Skipping fixture cleanup: A shared database or collection must be returned to a known state before each test.
8. Practice exercise
Apply the following exercise to the existing test project:
- Create an OrderBuilder that produces a valid order with sensible defaults.
- Add three factory methods for a single-item order, a bulk order, and an empty order.
- Test the total calculation with at least three data sets using Theory.
- Replace direct system-clock access with an IClock abstraction and use a fixed clock in the test.
- Run the tests repeatedly and in different orders. Verify that no test depends on data created by an earlier test.
As a final check, change the data used by one test and confirm that the other tests still pass. If another result changes, look for shared mutable state or missing cleanup.
Conclusion
Repeatable tests require more than correct assertions. The way test data is created is also part of test quality. Builders make complex objects readable, factories give names to business scenarios, fixtures provide controlled sharing for expensive setup, and parameterized tests verify one behavior across multiple inputs.
The central principle is to reduce dependencies between tests. Every test should start from a known state, time and randomness should be controllable, and the data used by a failing test should be easy to understand. In the next stage, we will apply these techniques to ASP.NET Core integration tests together with WebApplicationFactory and database seeding.