skip to content

In AutoFixture, what do Create, Build<T>().With and Freeze do, and how does AutoMoqCustomization supply a service's constructor dependencies?

level: middleimportance: should knowfreq 34%

answer

  1. anonymous values, not realistic ones
  2. Build is a one-off recipe
  3. Freeze = Create, then Inject
  4. interfaces become Mock<T>.Object
  5. ConfigureMembers fills return values

basics

~20 s

Create<T>() builds an anonymous T, filling constructor arguments and writable properties. Build<T>().With(...).Create() overrides chosen members once. Freeze<T>() creates a value and makes the fixture return it for every later request. AutoMoqCustomization turns interface requests into Moq mocks.

solid answer

~40 s

AutoFixture's `Fixture` creates **anonymous** test data: values the test does not care about. `fixture.Create<Patient>()` calls a constructor and fills writable properties; strings come out as the member name followed by a GUID, and `CreateMany<T>()` returns three items by default. `fixture.Build<Patient>().With(p => p.Status, PatientStatus.Active).Without(p => p.Appointments).Create()` customises one object without changing the fixture. `Freeze<T>()` creates a value and injects it, so every later request for `T` gets the same instance. With `fixture.Customize(new AutoMoqCustomization())`, a request for an interface such as `IPatientRepository` is answered with a `Mock<IPatientRepository>`'s `Object`. So I freeze `Mock<IPatientRepository>` **before** `Create<AppointmentScheduler>()`, set it up, and the scheduler receives that mock. `ConfigureMembers = true` also makes the mock's members return fixture-created values instead of Moq's defaults.

code

csharp · 14 lines
csharp
var fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });

var patients = fixture.Freeze<Mock<IPatientRepository>>();   // before the SUT

var patient = fixture.Build<Patient>()
    .With(p => p.Status, PatientStatus.Active)
    .Without(p => p.Appointments)
    .Create();

patients.Setup(r => r.FindAsync(patient.Id, It.IsAny<CancellationToken>()))
        .ReturnsAsync(patient);

var scheduler = fixture.Create<AppointmentScheduler>();      // gets patients.Object
var result = await scheduler.BookAsync(patient.Id, fixture.Create<DateTime>());

go deeper

for a junior

Remember the verbs: Create for a value, Build...With...Create for one tweaked object, Freeze for a shared instance, AutoMoqCustomization for interfaces.

for a middle

Explain the mechanics: Freeze is Create plus Inject, interface requests are relayed to Mock<T>.Object, and ConfigureMembers fills the mocks' return values.

for a senior

Use AutoFixture to keep tests stable as constructors grow, but set every value the outcome depends on explicitly, and handle recursion in entity graphs.

for a principal

Decide where anonymous data belongs: auto-mocked unit tests benefit, while integration tests usually need realistic, valid data from Bogus or builders.

## Anonymous data Most values in a unit test are there only because a constructor or a method demands them. AutoFixture's idea is that the test should not have to invent them: a `Fixture` creates **anonymous** values, and the test states only the values that matter. This is the opposite emphasis from Bogus, which aims for realistic data. ## Create and CreateMany - `fixture.Create<int>()`, `Create<string>()`, `Create<DateTime>()` return values of the type; a string is the member or parameter name followed by a GUID, so `Patient.LastName` becomes something like `LastName` plus a GUID. - `fixture.Create<Patient>()` calls a constructor with created arguments, then assigns created values to writable properties. - `fixture.CreateMany<Patient>()` returns **three** by default (`fixture.RepeatCount`); `CreateMany<Patient>(10)` returns ten. Two failures to recognise: 1. An **interface or abstract class** cannot be created by a plain fixture; it throws `ObjectCreationException`, suggesting you register a builder for it. 2. An object graph with a **cycle**, such as `Patient.Appointments` whose `Appointment.Patient` points back, throws `ObjectCreationExceptionWithPath` because the default `ThrowingRecursionBehavior` is installed. Remove it and add `OmitOnRecursionBehavior`, or use `Without` to skip the navigation. ## Build and Customize `Build<T>()` starts a one-off recipe that ends with `Create()` or `CreateMany()`: | Call | Effect | |---|---| | `With(p => p.Status, PatientStatus.Active)` | sets a member to a value | | `With(p => p.Email, () => $"{Guid.NewGuid()}@clinic.test")` | sets a member from a factory per object | | `Without(p => p.Appointments)` | leaves a member unset | | `OmitAutoProperties()` | fills no properties except those named with `With` | | `Do(p => p.Tags.Add("vip"))` | runs an action on the created object | The recipe affects only that call. `fixture.Customize<Patient>(c => c.Without(p => p.Appointments))` registers the same composition for every later `Patient` the fixture creates. ## Freeze `fixture.Freeze<T>()` is `Create<T>()` followed by `Inject(value)`: it returns a value and registers it, so from then on every request for `T`, directly or as a constructor argument, yields **that instance**. Order is therefore significant: freeze first, create the consumer second. ## AutoMoqCustomization The `AutoFixture.AutoMoq` package adds Moq. After `fixture.Customize(new AutoMoqCustomization())`: - a request for `Mock<IPatientRepository>` creates a mock; - a request for `IPatientRepository` itself is relayed to a mock and answered with its `Object`; - so `fixture.Create<AppointmentScheduler>()` succeeds even though its constructor needs three interfaces. The usual unit-test shape for the clinic scheduler: 1. `var repo = fixture.Freeze<Mock<IPatientRepository>>();` 2. set up `repo` for the call the test is about; 3. `var scheduler = fixture.Create<AppointmentScheduler>();` which receives `repo.Object`; 4. act, then assert or verify on `repo`. By default the mocks' members return Moq's own defaults. `new AutoMoqCustomization { ConfigureMembers = true }` makes their properties and virtual methods return fixture-created values instead. The older `AutoConfiguredMoqCustomization` is `[Obsolete]` and points to `ConfigureMembers = true`. `GenerateDelegates = true` makes delegate requests return mocked delegates. ## When it helps and when it hurts - It shines when constructors grow: adding a fourth dependency to `AppointmentScheduler` does not touch a single test that does not care about it. - It hurts when the test's meaning depends on a value the fixture chose silently. A test whose outcome depends on a patient's date of birth should set it with `With`, so the reader sees it. - It is not a source of realistic data: an e-mail property gets `Email` plus a GUID, which fails any validator that checks for an `@`. ## AutoFixture beside Bogus | | AutoFixture | Bogus | |---|---|---| | Goal | anonymous values nobody reads | realistic values that look like production | | Configuration | none needed to start; `Build`/`Customize` to override | a rule per member | | Constructors | fills arguments, including mocks with AutoMoq | `Activator.CreateInstance<T>()` or `CustomInstantiator` | | Typical home | unit tests of services with many dependencies | integration tests and seeded demo data | The two combine well: a fixture customization can delegate `Patient` creation to a Bogus faker, so services get auto-mocked dependencies and entities get plausible data.

  • Why must Freeze come before Create of the service under test?
    `Freeze<T>()` registers the instance at the moment it is called. If `Create<AppointmentScheduler>()` runs first, the fixture builds a fresh mock for the scheduler's constructor, and the mock you freeze afterwards is a different object, so its setups never reach the scheduler and verifications see no calls.
  • What is the difference between Build<Patient>().With(...) and Customize<Patient>(...)?
    `Build<Patient>()` composes a recipe for that one call and leaves the fixture unchanged. `Customize<Patient>(c => c.With(...))` registers the composition in the fixture, so every later `Patient`, including those created as constructor arguments or by `CreateMany`, follows it.

  • Freeze the mock after creating the service; the fixture updates it automatically.
  • AutoFixture produces realistic names and valid e-mail addresses out of the box.
  • A plain Fixture can create IPatientRepository without any customization.
  • Build<T>().With(...) changes every later Create<T>() on the same fixture.
  • Use AutoConfiguredMoqCustomization as the current way to configure mock members.