Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.
Test Data Builder Pattern
Applicable Scenarios
Test Data Builder Pattern is a Builder Pattern variant specifically designed for testing, used to create clear,
maintainable, and semantically explicit test data. This pattern is especially suitable for handling complex objects with
multiple attributes, making test code more readable and reducing maintenance costs.
Core Concepts
What is Test Data Builder Pattern?
Test Data Builder Pattern is an improved version of Object Mother Pattern, mainly solving the following problems:
- Fixed test data problem: Object Mother provides fixed test objects, difficult to adjust for specific test
scenarios
- Unclear test intent: When creating objects directly, test focus is easily obscured by large amounts of attribute
settings
- Repeated code: Similar object creation logic repeated in multiple tests
Why Need Builder Pattern?
Traditional test data creation problems
Too many parameter settings, unclear test intent.
Using Builder Pattern improvement
Intent is explicit, only set properties test cares about.
Implementation Guide
Basic Builder Structure
A standard Test Data Builder should contain:
- Default values: Provide reasonable defaults for all necessary properties
- Fluent interface: Use
With* method chain to set properties
- Semantic methods: Provide meaningful default creators (like
AnAdminUser(), ARegularUser())
- Build method: Finally create and return target object
Complete Builder Example
public class UserBuilder
{
// Default values: provide reasonable defaults for all properties
private string _name = "Default User";
private string _email = "default@example.com";
private int _age = 25;
private List<string> _roles = new();
private UserSettings _settings = new()
{
Theme = "Light",
Language = "en-US"
};
private bool _isActive = true;
private DateTime _createdAt = DateTime.UtcNow;
// With* methods: fluent interface to set individual properties
public UserBuilder WithName(string name)
{
_name = name;
return this;
}
public UserBuilder WithEmail(string email)
{
_email = email;
return this;
}
public UserBuilder WithAge(int age)
{
_age = age;
return this;
}
public UserBuilder WithRole(string role)
{
_roles.Add(role);
return this;
}
public UserBuilder WithRoles(params string[] roles)
{
_roles.AddRange(roles);
return this;
}
public UserBuilder IsInactive()
{
_isActive = false;
return this;
}
// Semantic default creators: provide quick creation methods for common scenarios
public static UserBuilder AUser() => new();
public static UserBuilder AnAdminUser() => new UserBuilder()
.WithRoles("Admin", "User");
public static UserBuilder ARegularUser() => new UserBuilder()
.WithRole("User");
// Build method: create final object
public User Build()
{
return new User
{
Name = _name,
Email = _email,
Age = _age,
Roles = _roles.ToArray(),
Settings = _settings,
IsActive = _isActive,
CreatedAt = _createdAt
};
}
}
```text
## Using Builder in Tests
### Single Test Scenario
```csharp
[Fact]
public void CreateUser_ValidAdminUser_ShouldCreateSuccessfully()
{
// Arrange - use Builder to create test data
var adminUser = UserBuilder
.AnAdminUser()
.WithName("John Admin")
.WithEmail("john.admin@company.com")
.WithAge(35)
.Build();
var userService = new UserService();
// Act
var result = userService.CreateUser(adminUser);
// Assert
Assert.NotNull(result);
Assert.Equal("John Admin", result.Name);
Assert.Contains("Admin", result.Roles);
}
```text
### Using with Theory
```csharp
public class UserValidationTests
{
[Theory]
[MemberData(nameof(GetUserScenarios))]
public void ValidateUser_DifferentUserScenarios_ShouldReturnCorrectValidationResult(User user, bool expected)
{
var validator = new UserValidator();
var result = validator.IsValid(user);
Assert.Equal(expected, result);
}
public static IEnumerable<object[]> GetUserScenarios()
{
// Valid user scenario
yield return new object[]
{
UserBuilder.AUser()
.WithName("Valid User")
.WithEmail("valid@example.com")
.WithAge(25)
.Build(),
true
};
// Invalid user scenario - empty name
yield return new object[]
{
UserBuilder.AUser()
.WithName("")
.Build(),
false
};
}
}
```text
## Best Practices
### 1. Provide Reasonable Default Values
Good practice: defaults make object in valid state.
### 2. Use Semantic Naming
Good practice: method names express test intent.
### 3. Composition Between Builders
Good practice: Builders can be combined.
### 4. Avoid Over-complication
Keep Builder simple, don't include complex business logic.
### 5. Unified Test Data Management
Good practice: create shared test data class.
## Comparison with Other Patterns
### Test Data Builder vs. Object Mother
| Characteristic | Test Data Builder | Object Mother |
| -------- | --------------------------- | --------------------- |
| Flexibility | Highly flexible, adjustable per test | Fixed test data |
| Readability | Fluent interface, explicit intent | Need to view method implementation |
| Maintainability | Centralized management, easy to modify | Changes affect all tests |
| Usage scenarios | Unit tests, scenario tests | Simple integration tests |
### Test Data Builder vs. AutoFixture
| Characteristic | Test Data Builder | AutoFixture |
| ---------- | ----------------------- | ------------------------- |
| Control degree | Full control over object creation | Auto-generate, lower control |
| Setup complexity | Need to manually create Builder | Almost zero setup |
| Test intent | Very explicit | Need additional explanation |
| Suitable timing | Tests needing precise control | Bulk data generation, anonymous testing |
## Practical Examples
Please refer to `templates/` directory for complete implementation examples.
## Reference Resources
### Original Articles
This skill content is extracted from "Old School Software Engineer's Testing Practice - 30 Day Challenge" series.
### Extended Reading
- **Test Data Builder Original Article**: [Test Data Builders: an alternative to the Object Mother pattern](http://www.natpryce.com/articles/000714.html) by Nat Pryce
### Related Skills
- `autofixture-basics` - Using AutoFixture to auto-generate test data
- `xunit-project-setup` - xUnit test project basic setup
- `test-naming-conventions` - Test naming conventions
## Summary
Test Data Builder Pattern is an important technique for writing maintainable tests:
- **When to use**: Test objects have multiple attributes, need to reuse test data, want to express clear intent
- **Core advantages**: Improve readability, reduce maintenance costs, enhance expressiveness
- **Notes**: Keep Builder simple, provide reasonable defaults, use semantic method names
1---2name: dotnet-testing-test-data-builder-pattern-43category: testing4subcategory: fundamentals5description: |6 Test Data Builder Pattern complete implementation guide. Used when using builder pattern to create maintainable test data or simplify complex object test preparation. Covers fluent interface, semantic methods, default value design, and Builder composition patterns.7 Keywords: test data builder, builder pattern test, test data builder, object mother, fluent interface, fluent interface, UserBuilder, ProductBuilder, .With(), .Build(), AUser(), test data preparation, complex object creation, semantic testing8targets: ['*']9license: MIT10metadata:11 source: https://skillmd.com/skills/rudironsoni/dotnet-testing-test-data-builder-pattern-412 author: Kevin Tseng13 version: '1.0.0'14 tags: 'test-data-builder, builder-pattern, fluent-interface, test-readability'15 related_skills: 'autofixture-basics, bogus-fake-data, autofixture-bogus-integration'16claudecode: {}17opencode: {}18codexcli:19 short-description: '.NET skill guidance for dotnet-testing-test-data-builder-pattern'20copilot: {}21geminicli: {}22antigravity: {}23---2425Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.2627# Test Data Builder Pattern2829## Applicable Scenarios3031Test Data Builder Pattern is a Builder Pattern variant specifically designed for testing, used to create clear,32maintainable, and semantically explicit test data. This pattern is especially suitable for handling complex objects with33multiple attributes, making test code more readable and reducing maintenance costs.3435## Core Concepts3637### What is Test Data Builder Pattern?3839Test Data Builder Pattern is an improved version of Object Mother Pattern, mainly solving the following problems:40411. **Fixed test data problem**: Object Mother provides fixed test objects, difficult to adjust for specific test42 scenarios432. **Unclear test intent**: When creating objects directly, test focus is easily obscured by large amounts of attribute44 settings453. **Repeated code**: Similar object creation logic repeated in multiple tests4647### Why Need Builder Pattern?4849### Traditional test data creation problems5051Too many parameter settings, unclear test intent.5253### Using Builder Pattern improvement5455Intent is explicit, only set properties test cares about.5657## Implementation Guide5859### Basic Builder Structure6061A standard Test Data Builder should contain:62631. **Default values**: Provide reasonable defaults for all necessary properties642. **Fluent interface**: Use `With*` method chain to set properties653. **Semantic methods**: Provide meaningful default creators (like `AnAdminUser()`, `ARegularUser()`)664. **Build method**: Finally create and return target object6768### Complete Builder Example6970````csharp71public class UserBuilder72{73 // Default values: provide reasonable defaults for all properties74 private string _name = "Default User";75 private string _email = "default@example.com";76 private int _age = 25;77 private List<string> _roles = new();78 private UserSettings _settings = new()79 {80 Theme = "Light",81 Language = "en-US"82 };83 private bool _isActive = true;84 private DateTime _createdAt = DateTime.UtcNow;8586 // With* methods: fluent interface to set individual properties87 public UserBuilder WithName(string name)88 {89 _name = name;90 return this;91 }9293 public UserBuilder WithEmail(string email)94 {95 _email = email;96 return this;97 }9899 public UserBuilder WithAge(int age)100 {101 _age = age;102 return this;103 }104105 public UserBuilder WithRole(string role)106 {107 _roles.Add(role);108 return this;109 }110111 public UserBuilder WithRoles(params string[] roles)112 {113 _roles.AddRange(roles);114 return this;115 }116117 public UserBuilder IsInactive()118 {119 _isActive = false;120 return this;121 }122123 // Semantic default creators: provide quick creation methods for common scenarios124 public static UserBuilder AUser() => new();125126 public static UserBuilder AnAdminUser() => new UserBuilder()127 .WithRoles("Admin", "User");128129 public static UserBuilder ARegularUser() => new UserBuilder()130 .WithRole("User");131132 // Build method: create final object133 public User Build()134 {135 return new User136 {137 Name = _name,138 Email = _email,139 Age = _age,140 Roles = _roles.ToArray(),141 Settings = _settings,142 IsActive = _isActive,143 CreatedAt = _createdAt144 };145 }146}147```text148149## Using Builder in Tests150151### Single Test Scenario152153```csharp154[Fact]155public void CreateUser_ValidAdminUser_ShouldCreateSuccessfully()156{157 // Arrange - use Builder to create test data158 var adminUser = UserBuilder159 .AnAdminUser()160 .WithName("John Admin")161 .WithEmail("john.admin@company.com")162 .WithAge(35)163 .Build();164165 var userService = new UserService();166167 // Act168 var result = userService.CreateUser(adminUser);169170 // Assert171 Assert.NotNull(result);172 Assert.Equal("John Admin", result.Name);173 Assert.Contains("Admin", result.Roles);174}175```text176177### Using with Theory178179```csharp180public class UserValidationTests181{182 [Theory]183 [MemberData(nameof(GetUserScenarios))]184 public void ValidateUser_DifferentUserScenarios_ShouldReturnCorrectValidationResult(User user, bool expected)185 {186 var validator = new UserValidator();187 var result = validator.IsValid(user);188 Assert.Equal(expected, result);189 }190191 public static IEnumerable<object[]> GetUserScenarios()192 {193 // Valid user scenario194 yield return new object[]195 {196 UserBuilder.AUser()197 .WithName("Valid User")198 .WithEmail("valid@example.com")199 .WithAge(25)200 .Build(),201 true202 };203204 // Invalid user scenario - empty name205 yield return new object[]206 {207 UserBuilder.AUser()208 .WithName("")209 .Build(),210 false211 };212 }213}214```text215216## Best Practices217218### 1. Provide Reasonable Default Values219220Good practice: defaults make object in valid state.221222### 2. Use Semantic Naming223224Good practice: method names express test intent.225226### 3. Composition Between Builders227228Good practice: Builders can be combined.229230### 4. Avoid Over-complication231232Keep Builder simple, don't include complex business logic.233234### 5. Unified Test Data Management235236Good practice: create shared test data class.237238## Comparison with Other Patterns239240### Test Data Builder vs. Object Mother241242| Characteristic | Test Data Builder | Object Mother |243| -------- | --------------------------- | --------------------- |244| Flexibility | Highly flexible, adjustable per test | Fixed test data |245| Readability | Fluent interface, explicit intent | Need to view method implementation |246| Maintainability | Centralized management, easy to modify | Changes affect all tests |247| Usage scenarios | Unit tests, scenario tests | Simple integration tests |248249### Test Data Builder vs. AutoFixture250251| Characteristic | Test Data Builder | AutoFixture |252| ---------- | ----------------------- | ------------------------- |253| Control degree | Full control over object creation | Auto-generate, lower control |254| Setup complexity | Need to manually create Builder | Almost zero setup |255| Test intent | Very explicit | Need additional explanation |256| Suitable timing | Tests needing precise control | Bulk data generation, anonymous testing |257258## Practical Examples259260Please refer to `templates/` directory for complete implementation examples.261262## Reference Resources263264### Original Articles265266This skill content is extracted from "Old School Software Engineer's Testing Practice - 30 Day Challenge" series.267268### Extended Reading269270- **Test Data Builder Original Article**: [Test Data Builders: an alternative to the Object Mother pattern](http://www.natpryce.com/articles/000714.html) by Nat Pryce271272### Related Skills273274- `autofixture-basics` - Using AutoFixture to auto-generate test data275- `xunit-project-setup` - xUnit test project basic setup276- `test-naming-conventions` - Test naming conventions277278## Summary279280Test Data Builder Pattern is an important technique for writing maintainable tests:281282- **When to use**: Test objects have multiple attributes, need to reuse test data, want to express clear intent283- **Core advantages**: Improve readability, reduce maintenance costs, enhance expressiveness284- **Notes**: Keep Builder simple, provide reasonable defaults, use semantic method names285````