Lesson 37 of 93 · 5 min read · Updated

Test Data Builders and Object Mothers for Readable C# Unit Tests

Every test needs data, and the way you create it decides how readable the test is. If each test builds its objects with long constructor calls, the reader cannot tell which value matters for the scenario. This lesson shows two patterns that fix this: the Test Data Builder, which supplies safe defaults and lets a test change only what matters, and the Object Mother, which gives common scenarios a name.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2
  4. No extra packages: both patterns are plain C#

The Problem with Inline Construction

The Coupon record has three values: a code, a discount rate and an expiry date.

M05.TestableDesign/Domain/Coupon.cs

public sealed record Coupon(string Code, decimal DiscountRate, DateTimeOffset ExpiresAt)
{
public bool IsValidAt(DateTimeOffset instant) => instant < ExpiresAt;
}

A test for an expired coupon could write new Coupon("BAHAR10", 0.10m, new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.Zero)). That line has three problems. The reader must work out which of the three values the test is about. Every test repeats the same noise. And when the record gains a fourth parameter, every one of those lines stops compiling.

The Test Data Builder

A builder holds a valid default for every field. A test calls only the With... methods for the fields that matter in its scenario, then calls Build().

M05.TestableDesign.Tests/Builders/CouponBuilder.cs

using M05.TestableDesign.Domain;

namespace M05.TestableDesign.Tests.Builders;

/// <summary>
/// "Build test data on purpose": the BUILDER pattern.
///
/// The builder provides SAFE DEFAULTS; a test changes only the field that is
/// IMPORTANT for its scenario. The reader then understands:
/// "the only thing that matters here is the expiry date".
/// </summary>
public sealed class CouponBuilder
{
private string _code = "BAHAR10";
private decimal _rate = 0.10m;
private DateTimeOffset _expiresAt = new(2026, 12, 31, 23, 59, 59, TimeSpan.Zero);

public CouponBuilder WithCode(string code) { _code = code; return this; }

public CouponBuilder WithRate(decimal rate) { _rate = rate; return this; }

public CouponBuilder ExpiringAt(DateTimeOffset expiresAt) { _expiresAt = expiresAt; return this; }

/// <summary>Readable shortcut for the expired-coupon scenario.</summary>
public CouponBuilder AlreadyExpired() =>
ExpiringAt(new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.Zero));

public Coupon Build() => new(_code, _rate, _expiresAt);
}

Each method returns this, so calls chain into a fluent line. The defaults are chosen so that an unmodified build produces a normal, valid coupon. AlreadyExpired() is a domain-named shortcut: the test says what it means instead of how to compute it.

The builder is also the only place that calls the Coupon constructor. If the record gets a new parameter, you add one field with a default to the builder, and no test has to change.

M05.TestableDesign.Tests/TestDataGenerationTests.cs

[Fact]
public void Builder_MakesTheImportantFieldObvious()
{
// The reader sees at once: the only thing that matters in this test is the RATE.
var coupon = new CouponBuilder().WithRate(0.25m).Build();

coupon.DiscountRate.Should().Be(0.25m);
coupon.Code.Should().Be("BAHAR10", "diğer alanlar güvenli varsayılanlardır");
}

The second assertion uses the FluentAssertions "because" argument to record that the code is a safe default (the Turkish text reads "the other fields are safe defaults"). In a real test you would not assert on the default at all; this test exists to show the pattern.

The Object Mother

A builder answers "how do I build this?". An Object Mother answers "which scenario is this?". It is a static class with named factory methods for the cases your tests use again and again.

M05.TestableDesign.Tests/Builders/CouponBuilder.cs

/// <summary>
/// OBJECT MOTHER pattern: named, canonical examples.
/// The Builder describes "how it is built", the Object Mother describes "which scenario".
/// The two work very well together.
/// </summary>
public static class Coupons
{
public static Coupon TenPercentValid() => new CouponBuilder().Build();

public static Coupon TenPercentExpired() => new CouponBuilder().AlreadyExpired().Build();

public static Coupon HalfPrice() => new CouponBuilder().WithCode("YARIYIL50").WithRate(0.50m).Build();
}

The mother is built on top of the builder, so there is still only one place that knows the constructor. Each method name describes the case in business terms.

M05.TestableDesign.Tests/TestDataGenerationTests.cs

[Fact]
public void ObjectMother_NamesTheScenario()
{
// The name "TenPercentExpired" describes the scenario in one word.
var coupon = Coupons.TenPercentExpired();

coupon.IsValidAt(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero))
.Should().BeFalse();
}

Using Both in a Real Test

The patterns pay off in tests with mocks, where the Arrange section is already busy. Here a repository double returns a coupon from the Object Mother.

M05.TestableDesign.Tests/MoqBasicsTests.cs

[Fact]
public async Task PayAsync_WithExpiredCoupon_ChargesFullAmount()
{
var (sut, gateway, coupons) = CreateSut();

coupons
.Setup(x => x.FindAsync("BAHAR10", It.IsAny<CancellationToken>()))
.ReturnsAsync(Coupons.TenPercentExpired());

gateway
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Authorization.Approve("AUTH-FULL"));

var result = await sut.PayAsync(Money.Try(1_000m), "BAHAR10");

// An expired coupon applies NO discount.
result.Charged.Amount.Should().Be(1_000m);
}

Coupons.TenPercentExpired() tells the reader everything about the coupon in two words. Without it, the Arrange section would contain a date literal and the reader would have to compare it with the fake clock to see that it lies in the past.

When to Use Which

SituationUse
A test needs one field set to a specific valueBuilder with one With... call
Several tests share the same named caseObject Mother method
A new case appears in only one testBuilder inline; promote to the mother if it repeats

A common mistake is to let the Object Mother grow into dozens of near-identical methods such as TenPercentExpiredWithLongCode. When a method name starts listing field values, go back to the builder for that test. Another mistake is to hide the important value inside a default. If the test is about the discount rate, write .WithRate(0.25m) in the test even if the default happens to be correct, so the reader can see it.

Summary

  1. Inline constructor calls hide which value matters and break when the type changes.
  2. A Test Data Builder provides safe defaults; the test sets only the fields its scenario depends on.
  3. An Object Mother gives repeated scenarios business names such as TenPercentExpired().
  4. Build the mother on top of the builder so only one place calls the constructor.
  5. Always state the value that matters for the test explicitly, even when the default would match.