Lesson 38 of 93 · 5 min read · Updated

Generating Test Data with AutoFixture and Bogus Without Hiding the Scenario

Hand-written builders are clear, but writing one for every type takes time. Two libraries can fill objects for you. AutoFixture creates instances of any type with anonymous values, so you only set the fields that matter. Bogus generates realistic fake data such as names, e-mail addresses and cities. Both are useful, and both can make a test worse if the generated values hide the scenario. This lesson shows how to use them safely.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2
  4. AutoFixture 4.18.1
  5. Bogus 35.6.5

AutoFixture: Fill the Fields You Do Not Care About

AutoFixture's Fixture can create an instance of almost any type. It finds a constructor, generates a value for each parameter and returns the object. With Build<T>() you can pin specific members and let AutoFixture fill the rest.

M05.TestableDesign.Tests/TestDataGenerationTests.cs

[Fact]
public void AutoFixture_FillsIrrelevantFields()
{
var fixture = new Fixture();

// We FIX the fields that matter for the scenario...
var coupon = fixture.Build<Coupon>()
.With(c => c.DiscountRate, 0.15m)
.With(c => c.ExpiresAt, new DateTimeOffset(2030, 1, 1, 0, 0, 0, TimeSpan.Zero))
// ...we do not care about Code, so AutoFixture fills it.
.Create();

coupon.DiscountRate.Should().Be(0.15m);
coupon.Code.Should().NotBeNullOrWhiteSpace();
}

The test states two facts: the rate is 15 percent and the coupon expires in 2030. The code is noise for this scenario, so AutoFixture fills it with a generated string. When Coupon gains a new property, this test still compiles and AutoFixture fills the new property too.

The important rule is in the comment: the value the scenario depends on must be set explicitly. If this test relied on AutoFixture to produce a future expiry date, it would depend on what AutoFixture happens to generate for a DateTimeOffset. That is a hidden assumption and a source of random failures.

Freeze: One Instance for the Whole Graph

Freeze<T>() tells the fixture to return the same instance every time it needs a T. This matters when several objects in a graph must share a value, for example the same customer id or the same currency.

M05.TestableDesign.Tests/TestDataGenerationTests.cs

[Fact]
public void AutoFixture_Freeze_KeepsTheSameInstanceAcrossTheGraph()
{
var fixture = new Fixture();

// Freeze: EVERY object of this type created from now on is this instance.
// Critical when you need repeatability.
var frozenCurrency = fixture.Freeze<string>();

var first = fixture.Create<string>();
var second = fixture.Create<string>();

first.Should().Be(frozenCurrency);
second.Should().Be(frozenCurrency);
}

In larger tests Freeze is often used with a mock: freeze a Mock<IRepository>, then let AutoFixture create the system under test. The class receives the same frozen mock that the test configures. That combination needs the AutoFixture.AutoMoq package, which this lesson does not use.

Bogus: Realistic Data with a Fixed Seed

AutoFixture's strings look like Code3f2a.... That is fine for fields nobody reads. When the data must look real, for example for a display name, an e-mail validation or a demo screenshot, use Bogus. A Faker<T> describes a rule for each property.

M05.TestableDesign.Tests/TestDataGenerationTests.cs

[Fact]
public void Bogus_ProducesRealisticButRepeatableData()
{
// FIXED SEED: run the same test 1000 times and it produces the same data.
// Without a seed the test passes today, fails tomorrow, and you cannot reproduce it.
var faker = new Faker<CustomerProfile>("tr")
.UseSeed(20260314)
.RuleFor(c => c.FullName, f => f.Name.FullName())
.RuleFor(c => c.Email, (f, c) => f.Internet.Email(c.FullName))
.RuleFor(c => c.City, f => f.Address.City());

var first = faker.Generate();

var sameFaker = new Faker<CustomerProfile>("tr")
.UseSeed(20260314)
.RuleFor(c => c.FullName, f => f.Name.FullName())
.RuleFor(c => c.Email, (f, c) => f.Internet.Email(c.FullName))
.RuleFor(c => c.City, f => f.Address.City());

var second = sameFaker.Generate();

first.FullName.Should().Be(second.FullName);
first.Email.Should().Contain("@");
first.City.Should().NotBeNullOrWhiteSpace();
}

/// <summary>A simple customer profile for the Bogus example.</summary>
public sealed class CustomerProfile
{
public string FullName { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string City { get; set; } = string.Empty;
}

Three details are worth noting:

  1. "tr" selects the Turkish locale, so names and cities are Turkish. Bogus supports many locales; pick the one your validation rules expect.
  2. The e-mail rule uses the overload (f, c) => ..., which receives the object under construction. The e-mail is derived from the full name that was generated a moment earlier, so the two fields are consistent.
  3. UseSeed(20260314) makes the random sequence repeatable. Two fakers with the same seed and the same rules produce the same data. The test proves this by comparing first.FullName with second.FullName.

Why the Seed Matters

Without a seed, Bogus produces different data on every run. Suppose a name occasionally contains an apostrophe and your code fails on it. The test fails once on CI, you re-run it, it passes, and you cannot reproduce the failure. With a fixed seed, a failing run fails the same way every time, and you can debug it. If you want to explore many random inputs on purpose, log the seed you used so a failure can be replayed.

Choosing Between Builder, AutoFixture and Bogus

ToolBest forWatch out for
Builder / Object MotherDomain objects central to the scenarioWriting and maintaining one per type
AutoFixtureLarge object graphs with many irrelevant fieldsRelying on generated values for the scenario
BogusRealistic values: names, e-mails, addressesMissing seed, which makes failures unrepeatable

These tools can be combined. A builder can use Bogus for its defaults, and AutoFixture can fill a graph while the test pins one value with With.

Summary

  1. AutoFixture creates instances with generated values; use Build<T>().With(...) to pin the fields that matter.
  2. Never let a generated value decide the outcome of the scenario; set that value explicitly.
  3. Freeze<T>() makes every request for T return the same instance across the object graph.
  4. Bogus generates realistic data per locale, and rules can depend on earlier properties.
  5. Always pass UseSeed(...) to Bogus in tests so a failure can be reproduced.