Lesson 7 of 8
Testing Patterns - Builders & Object Mothers
Test data builders and Object Mother patterns prevent test brittleness: when the Product entity gains a new Required field, you update ONE builder, not 200 individual test setups. Keeps test code DRY and readable.
Builder Pattern for Test Data
// ━━ Product builder - fluent test data creation ━━
public class ProductBuilder
{
private Guid _id = Guid.NewGuid();
private string _name = "Test Widget";
private decimal _price = 9.99m;
private Guid _categoryId = Guid.NewGuid();
private int _stock = 100;
private bool _isActive = true;
private DateTime _createdAt = DateTime.UtcNow;
public ProductBuilder WithId(Guid id) { _id = id; return this; }
public ProductBuilder WithName(string name) { _name = name; return this; }
public ProductBuilder WithPrice(decimal price) { _price = price; return this; }
public ProductBuilder WithCategory(Guid categoryId) { _categoryId = categoryId; return this; }
public ProductBuilder WithStock(int stock) { _stock = stock; return this; }
public ProductBuilder OutOfStock() { _stock = 0; return this; }
public ProductBuilder Inactive() { _isActive = false; return this; }
public ProductBuilder CreatedDaysAgo(int days) { _createdAt = DateTime.UtcNow.AddDays(-days); return this; }
public Product Build() => new()
{
Id = _id,
Name = _name,
Price = _price,
CategoryId = _categoryId,
Stock = _stock,
IsActive = _isActive,
CreatedAt = _createdAt,
};
// Shortcut for common scenarios
public static Product OutOfStockProduct() => new ProductBuilder().OutOfStock().Build();
public static Product ExpensiveProduct() => new ProductBuilder().WithPrice(999.99m).Build();
public static List<Product> MultipleProducts(int count) =>
Enumerable.Range(1, count)
.Select(i => new ProductBuilder().WithName($"Product {i}").Build())
.ToList();
}
// ━━ Usage in tests - readable, DRY ━━
public class ProductValidatorTests
{
[Fact]
public void Validate_OutOfStockProduct_ShouldWarnOnPurchase()
{
var product = new ProductBuilder().OutOfStock().Build();
product.Stock.Should().Be(0);
product.IsActive.Should().BeTrue(); // still active, just no stock
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(-100)]
public void Validate_NegativeOrZeroPrice_ShouldBeInvalid(decimal price)
{
var product = new ProductBuilder().WithPrice(price).Build();
var validator = new ProductPriceValidator();
var result = validator.IsValid(product.Price);
result.Should().BeFalse();
}
}
class Product { public Guid Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; } public Guid CategoryId { get; set; } public int Stock { get; set; } public bool IsActive { get; set; } public DateTime CreatedAt { get; set; } }
class ProductPriceValidator { public bool IsValid(decimal price) => price > 0; }Tip
Tip
Practice Testing Patterns Builders Object Mothers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Testing Patterns Builders Object Mothers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Testing Patterns Builders Object Mothers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?