As a .NET application grows, its automated test suite usually grows with it. A service that initially requires only one or two objects for testing may eventually depend on several related entities, configuration values, and nested objects. Creating all these objects manually in every test can make the test code longer and harder to maintain.
Consider an application that manages customer orders. Testing an order service may require a customer, an address, several products, order items, payment details, and delivery information. If every test creates these objects independently, the same setup code gets repeated across the test suite.
This repetition creates a maintenance problem. When a new required property is added to the Order class, developers may need to update dozens of tests. Some tests may fail because they do not provide the new property, while others may continue using outdated or unrealistic test data.
A test data builder provides a simple solution. It centralizes object creation, provides sensible defaults, and lets individual tests override only the properties relevant to their scenarios.
This article explains how to build and use test data builders in C# with practical examples, xUnit, and modern .NET application design.
Understanding the Test Data Builder Pattern
A test data builder is a small class responsible for creating objects used in automated tests. Instead of constructing complex objects directly inside every test, developers use a builder that provides default values and customization methods.
For example, consider the following Order class:
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public string Status { get; set; } = string.Empty;
public decimal TotalAmount { get; set; }
public List<OrderItem> Items { get; set; } = new();
}An order also contains individual items.
public class OrderItem
{
public int ProductId { get; set; }
public string ProductName { get; set; } = string.Empty;
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
}A test that creates an order manually might look like this:
[Fact]
public void CalculateTotal_ShouldReturnCorrectAmount()
{
var order = new Order
{
Id = 101,
CustomerId = 5001,
CreatedAt = DateTimeOffset.UtcNow,
Status = "Pending",
TotalAmount = 1500,
Items = new List<OrderItem>
{
new()
{
ProductId = 10,
ProductName = "Keyboard",
Quantity = 2,
UnitPrice = 500
},
new()
{
ProductId = 11,
ProductName = "Mouse",
Quantity = 1,
UnitPrice = 500
}
}
};
// Execute the test scenario.
}This setup is understandable for one test. However, if ten different tests require a similar order, the same object creation code may appear repeatedly.
A builder moves this responsibility into one reusable location.
Creating Your First Test Data Builder
Start by creating a class named OrderBuilder. The builder should contain default values that represent a valid order.
public class OrderBuilder
{
private readonly Order _order;
public OrderBuilder()
{
_order = new Order
{
Id = 101,
CustomerId = 5001,
CreatedAt = DateTimeOffset.UtcNow,
Status = "Pending",
TotalAmount = 1000,
Items = new List<OrderItem>
{
new()
{
ProductId = 10,
ProductName = "Keyboard",
Quantity = 1,
UnitPrice = 1000
}
}
};
}
public Order Build()
{
return _order;
}
}The Build method returns the object created by the builder.
A test can now create a valid order with one line of code.
[Fact]
public void CreateOrder_ShouldHaveDefaultValues()
{
var order = new OrderBuilder().Build();
Assert.Equal(101, order.Id);
Assert.Equal(5001, order.CustomerId);
Assert.Equal("Pending", order.Status);
}This is a useful starting point, but the builder currently provides only fixed values. Real test suites need to customize objects without creating a new builder for every scenario.
Adding Customization Methods
A builder becomes more useful when tests can change individual properties.
For example, one test may need a completed order, while another may need an order belonging to a different customer.
Add methods that update the relevant properties and return the same builder instance.
public class OrderBuilder
{
private readonly Order _order;
public OrderBuilder()
{
_order = new Order
{
Id = 101,
CustomerId = 5001,
CreatedAt = DateTimeOffset.UtcNow,
Status = "Pending",
TotalAmount = 1000,
Items = new List<OrderItem>
{
new()
{
ProductId = 10,
ProductName = "Keyboard",
Quantity = 1,
UnitPrice = 1000
}
}
};
}
public OrderBuilder WithId(int id)
{
_order.Id = id;
return this;
}
public OrderBuilder WithCustomerId(int customerId)
{
_order.CustomerId = customerId;
return this;
}
public OrderBuilder WithStatus(string status)
{
_order.Status = status;
return this;
}
public OrderBuilder WithTotalAmount(decimal amount)
{
_order.TotalAmount = amount;
return this;
}
public Order Build()
{
return _order;
}
}The builder now supports a fluent API. Each method changes one part of the object and returns the builder so that another customization method can be called.
A test can create a completed order without repeating the complete object initialization.
[Fact]
public void GetOrder_ShouldReturnCompletedOrder()
{
var order = new OrderBuilder()
.WithId(205)
.WithCustomerId(7001)
.WithStatus("Completed")
.WithTotalAmount(2500)
.Build();
Assert.Equal(205, order.Id);
Assert.Equal(7001, order.CustomerId);
Assert.Equal("Completed", order.Status);
Assert.Equal(2500, order.TotalAmount);
}This approach makes the test easier to read because the setup describes only the differences from the default object.
Supporting Nested Objects and Collections
In real applications, test objects often contain nested entities and collections. A builder should make these relationships easy to customize.
For example, an order may contain several items. Add a method that replaces the default collection with a collection supplied by the test.
public OrderBuilder WithItems(params OrderItem[] items)
{
_order.Items = items.ToList();
return this;
}You can also create a separate builder for order items.
public class OrderItemBuilder
{
private readonly OrderItem _item = new()
{
ProductId = 10,
ProductName = "Keyboard",
Quantity = 1,
UnitPrice = 1000
};
public OrderItemBuilder WithProductId(int productId)
{
_item.ProductId = productId;
return this;
}
public OrderItemBuilder WithProductName(string productName)
{
_item.ProductName = productName;
return this;
}
public OrderItemBuilder WithQuantity(int quantity)
{
_item.Quantity = quantity;
return this;
}
public OrderItemBuilder WithUnitPrice(decimal price)
{
_item.UnitPrice = price;
return this;
}
public OrderItem Build()
{
return _item;
}
}Now a test can create multiple order items without repeating their complete initialization.
[Fact]
public void CreateOrder_ShouldSupportMultipleItems()
{
var keyboard = new OrderItemBuilder()
.WithProductId(10)
.WithProductName("Keyboard")
.WithQuantity(2)
.WithUnitPrice(500)
.Build();
var mouse = new OrderItemBuilder()
.WithProductId(11)
.WithProductName("Mouse")
.WithQuantity(1)
.WithUnitPrice(500)
.Build();
var order = new OrderBuilder()
.WithItems(keyboard, mouse)
.WithTotalAmount(1500)
.Build();
Assert.Equal(2, order.Items.Count);
Assert.Equal(1500, order.TotalAmount);
}Separate builders are useful when nested objects have their own properties and are reused across multiple test scenarios.
However, do not create a builder for every small class automatically. A simple object with two or three properties may not need its own builder.
Preventing Shared Mutable State Between Tests
One important problem with test data builders is shared mutable state.
Consider this implementation:
public class OrderBuilder
{
private static readonly Order DefaultOrder = new()
{
Id = 101,
CustomerId = 5001,
Status = "Pending"
};
public Order Build()
{
return DefaultOrder;
}
}The DefaultOrder field is static. Every builder instance returns the same object.
If one test changes the status, another test may receive the modified object. This can create failures that depend on test execution order or parallel execution.
The safer approach is to create a new object for every builder instance.
public class OrderBuilder
{
private readonly Order _order = new()
{
Id = 101,
CustomerId = 5001,
Status = "Pending"
};
public Order Build()
{
return new Order
{
Id = _order.Id,
CustomerId = _order.CustomerId,
Status = _order.Status,
CreatedAt = _order.CreatedAt,
TotalAmount = _order.TotalAmount,
Items = _order.Items
.Select(item => new OrderItem
{
ProductId = item.ProductId,
ProductName = item.ProductName,
Quantity = item.Quantity,
UnitPrice = item.UnitPrice
})
.ToList()
};
}
}This version returns a new Order and copies its nested items. The test receives an independent object rather than a reference to the builder's internal state.
For larger object graphs, the copy logic may become expensive to maintain. In that situation, consider using immutable test data, dedicated copy methods, or a carefully designed factory.
The important rule is that tests should not unexpectedly share mutable objects.
Using Test Data Builders With xUnit Theory Tests
Builders are especially useful when the same test needs to run with multiple input values.
Suppose an order service should return only orders that belong to a particular customer. Instead of creating a complete order for every test case, use a builder to prepare the required objects.
public class OrderService
{
public List<Order> GetCustomerOrders(
IEnumerable<Order> orders,
int customerId)
{
return orders
.Where(order => order.CustomerId == customerId)
.ToList();
}
}The test can create several orders with different customer IDs.
[Theory]
[InlineData(5001, 2)]
[InlineData(7001, 1)]
[InlineData(9001, 0)]
public void GetCustomerOrders_ShouldFilterByCustomer(
int customerId,
int expectedCount)
{
var orders = new List<Order>
{
new OrderBuilder()
.WithCustomerId(5001)
.Build(),
new OrderBuilder()
.WithId(102)
.WithCustomerId(5001)
.Build(),
new OrderBuilder()
.WithId(103)
.WithCustomerId(7001)
.Build()
};
var service = new OrderService();
var result = service.GetCustomerOrders(
orders,
customerId);
Assert.Equal(expectedCount, result.Count);
}The test data builder keeps the object setup short while xUnit Theory allows the same behavior to be checked against multiple scenarios.
When to Use Builders, Object Mothers, and AutoFixture
There are several ways to create test data in .NET. A test data builder is one option, but it is not always the best choice.
Approach | Best use case | Main consideration |
|---|---|---|
Test Data Builder | Complex objects with customizable properties | Requires maintaining builder methods |
Object Mother | Reusable predefined business scenarios | Can become difficult to customize |
AutoFixture | Automatically generating object graphs | Generated values may not represent valid business scenarios |
Direct object initialization | Small and simple objects | Repeated setup can grow across tests |
Factory methods | Standard object creation with limited variations | Less flexible for many test-specific changes |
An Object Mother provides predefined objects such as PendingOrder, CompletedOrder, or CancelledOrder. It works well when tests repeatedly need the same business scenarios.
AutoFixture can automatically populate object properties and reduce manual setup. It is useful for large object graphs, but developers should still control values that influence business rules.
For most business-focused test suites, builders offer a useful balance between readability and control.
Common Mistakes to Avoid
A test data builder should simplify tests rather than introduce another complicated framework.
One common mistake is creating too many customization methods. If a builder exposes every property of a large entity, it may become as difficult to maintain as the original model. Add methods for properties that are commonly changed or important to test scenarios.
Another mistake is using unrealistic default values. For example, an order with a negative quantity or an invalid status should not be the default object if the application normally prevents those values. Defaults should represent a valid and meaningful business scenario.
Avoid hiding important test conditions inside the builder. If a test checks how an order behaves when payment fails, the test should clearly show that the payment status is configured as failed.
Also, do not let builders silently calculate business values unless that behavior is intentional. If an order total is calculated by the application, the test should normally exercise the calculation rather than have the builder duplicate the same business logic.
Finally, avoid using one builder instance across unrelated tests. Each test should create its own builder so that customization in one scenario cannot affect another.
Best Practices for Maintaining Builders in Large Test Suites
As the test suite grows, organize builders around the domain objects they create. For example, an Orders test folder may contain OrderBuilder and OrderItemBuilder, while a Customers folder may contain CustomerBuilder and AddressBuilder.
Keep default values realistic and consistent with the application's validation rules. When a required property is added to a domain model, update the corresponding builder so that existing tests continue to create valid objects.
Use clear method names such as WithStatus, WithCustomerId, and WithItems. These names make test setup easy to understand without requiring developers to inspect the builder implementation.
Keep builders focused on test data creation. They should not call databases, external APIs, or application services unless the test specifically requires an integration-level setup.
For database integration tests, builders can create entity objects, while separate test fixtures or setup helpers manage persistence and cleanup. Keeping these responsibilities separate makes the test suite easier to maintain.
Summary
Test data builders help .NET developers reduce repeated object initialization across large automated test suites. They provide sensible defaults, support fluent customization, and make test scenarios easier to understand.
A well-designed builder creates independent objects, handles nested collections carefully, and avoids hiding important business conditions. Separate builders can be introduced for complex nested entities, while simpler objects can continue using direct initialization.
The goal is not to build a large test data framework. It is to remove unnecessary setup repetition while keeping each test clear about what it is verifying. When used carefully, test data builders make growing .NET test suites easier to maintain and safer to change.


Join the conversation! Your thoughts help the community grow.