Constructor-first customization for AutoFixture with clean defaults, per-test overrides, and extension points for advanced object creation.
AutoFixture provides powerful Fixture creation and customization capabilities.
But it creates objects by setting properties after the constructor is called.
But what if you have Guards and follow the Always-Valid-Model principle?
ConstructorCustomization.AutoFixture provides a constructor-first customization model for AutoFixture. This is a package only built on AutoFixture and provides an ICustomization implementation with minimal effort to get started but highly extensible for advanced scenarios.
- Create simple objects in a one-liner.
- Use Fluent API to override defaults on a per-test basis.
- Explicitly map constructor parameters to properties.
- Pluggable extension model for matching and specimen/value creation behavior.
- Fully compatible with AutoFixture ecosystem and existing customizations.
Under the hood, ConstructorCustomization uses reflection to retrieve a constructor and matches property names to parameter names.
Values are created using AutoFixture's existing value creation.
Constructor selection, parameter matching and value creation can all be customized using the provided extension models.
dotnet add package ConstructorCustomization.AutoFixtureUse this when you want a fast start in a test.
using AutoFixture;
using ConstructorCustomization.AutoFixture;
var fixture = new Fixture();
fixture.Customize(new ConstructorCustomization<Person>()
.With(x => x.FirstName, "Ada")
.With(x => x.LastName, "Lovelace")
.Without(x => x.MiddleName));
var person = fixture.Create<Person>();For reusable test behavior, create a typed customization once and use it across many tests.
using AutoFixture;
using ConstructorCustomization.AutoFixture;
public class PersonCustomization : ConstructorCustomization<Person, PersonCustomization>
{
protected override Person CreateInstance(IFixture fixture)
{
SetDefault(x => x.FirstName, "Ada");
SetDefault(x => x.LastName, "Lovelace");
SetDefault(x => x.Age, 36);
return base.CreateInstance(fixture);
}
}
var fixture = new Fixture();
var customization = new PersonCustomization();
fixture.Customize(customization);
var defaultPerson = fixture.Create<Person>();
customization.With(x => x.Age, 18);
var youngPerson = fixture.Create<Person>();
customization.Clear();- Constructor-first object creation for test models.
- Stable defaults with
SetDefault(...). - Per-test overrides with
With(...)andWithout(...). - Explicit parameter-to-property mapping with
MatchParameterToProperty(...). - Deferred value generation with factory delegates.
- Pluggable extension model for matching and specimen/value creation behavior.
- Wiki home: Home
- Getting started: Getting Started
- Behavior customization: Customizing Behavior
- Extension points: Extensions Overview
- How it Works: Creation Pipeline
