skip to content

How do AutoFixture's [AutoData] and [Frozen] parameters work in xUnit theories, and what blocks them when the test project moves to xunit.v3?

level: seniorimportance: nice to knowfreq 20%

answer

  1. parameters become fixture requests
  2. [Frozen] parameter before the SUT
  3. derive a custom AutoDataAttribute
  4. AutoFixture.Xunit2 targets xUnit v2
  5. no xunit.v3 package in 4.18.1

basics

~20 s

[AutoData] fills every theory parameter from a Fixture, and [Frozen] freezes a parameter so later parameters receive the same instance. AutoFixture 4.18.1's AutoFixture.Xunit2 is built on xUnit v2's data-attribute contract and ships no xunit.v3 package.

solid answer

~40 s

With `AutoFixture.Xunit2`, `[Theory, AutoData]` creates a `Fixture` and resolves every parameter of the test from it, left to right. A parameter marked `[Frozen]` is frozen as it is created, so a later parameter, typically the service under test, receives that instance. That is why `[Frozen] Mock<IPatientRepository> repo, AppointmentScheduler sut` works and the reverse order does not. To add Moq, derive an attribute: `class AutoMoqDataAttribute() : AutoDataAttribute(() => new Fixture().Customize(new AutoMoqCustomization()))`. `[InlineAutoData(...)]` supplies the first values and generates the rest. The catch with xunit.v3: AutoFixture 4.18.1's attributes derive from xUnit v2's `Xunit.Sdk.DataAttribute` and the package depends on `xunit.extensibility.core` 2.x. xunit.v3's data attributes implement a different contract, `Xunit.v3.DataAttribute`, and AutoFixture 4.18.1 ships no package for it. A v3 project creates the `Fixture` in the test or a helper, or keeps that project on xUnit v2.

code

csharp · 14 lines
csharp
// xunit.v3: no [AutoData]; the same fixture, created in the test
[Fact]
public async Task Booking_an_inactive_patient_is_refused()
{
    var fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
    var patients = fixture.Freeze<Mock<IPatientRepository>>();
    var patient = fixture.Build<Patient>().With(p => p.Status, PatientStatus.Inactive).Create();
    patients.Setup(r => r.FindAsync(patient.Id, It.IsAny<CancellationToken>())).ReturnsAsync(patient);

    var sut = fixture.Create<AppointmentScheduler>();
    var result = await sut.BookAsync(patient.Id, new DateTime(2026, 3, 2, 9, 0, 0));

    Assert.False(result.Succeeded);
}

go deeper

for a junior

Recall that [AutoData] creates every theory parameter and [Frozen] makes later parameters share one instance.

for a middle

Explain left-to-right resolution, why [Frozen] must precede the service, and how a derived AutoDataAttribute adds AutoMoqCustomization.

for a senior

Plan the xunit.v3 migration: AutoFixture 4.18.1 has no v3 package, so decide between fixture-in-test, staying on v2 or a custom v3 attribute.

for a principal

Weigh convenience attributes against framework upgrades: features tied to one test framework's extension contract can block the whole suite's move.

## What the attributes do `AutoFixture.Xunit2` connects AutoFixture to xUnit **theories**: tests whose parameters come from a data attribute. ```csharp [Theory, AutoMoqData] public async Task Booking_an_inactive_patient_is_refused( [Frozen] Mock<IPatientRepository> patients, Patient patient, AppointmentScheduler sut) { patient.Status = PatientStatus.Inactive; patients.Setup(r => r.FindAsync(patient.Id, It.IsAny<CancellationToken>())).ReturnsAsync(patient); var result = await sut.BookAsync(patient.Id, new DateTime(2026, 3, 2, 9, 0, 0)); Assert.False(result.Succeeded); } ``` - **`[AutoData]`** (`AutoDataAttribute`) creates a fixture and asks it for one specimen per parameter, in declaration order. - **`[Frozen]`** (`FrozenAttribute`) freezes the parameter's value when it is created. By default it matches the exact type (`Matching.ExactType`); `[Frozen(Matching.ImplementedInterfaces)]` also serves requests for the interfaces the value implements. - **`[InlineAutoData("Okafor")]`** passes the given values to the first parameters and generates the rest. - **`[MemberAutoData(nameof(Slots))]`** does the same with values from a member. ## Order is the mechanism Parameters are resolved left to right, and freezing takes effect only when the frozen parameter is created. So: 1. `[Frozen] Mock<IPatientRepository> patients` creates the mock and freezes it; 2. `AppointmentScheduler sut` is created next, and its `IPatientRepository` argument is that frozen mock's `Object`; 3. setups on `patients` therefore reach the scheduler. Put `sut` first and it is built with a different mock; the test's setups then configure an object the scheduler never sees. ## Customising the fixture `AutoDataAttribute` has a protected constructor that takes a `Func<IFixture>`. Deriving from it is the supported way to add customizations: ```csharp public sealed class AutoMoqDataAttribute() : AutoDataAttribute( () => new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true })); ``` The constructor overload that takes a fixture `Type` is obsolete and marked as an error, and the one that takes an `IFixture` instance is obsolete for performance reasons; the factory overload creates the fixture lazily. ## The xunit.v3 gap Many new test projects start on **xunit.v3** with Microsoft.Testing.Platform (the `xunit3` template from `xunit.v3.templates`; the SDK's own `dotnet new xunit` still creates a v2 project). AutoFixture's latest release, **4.18.1**, ships: - `AutoFixture.Xunit` for xUnit v1; - `AutoFixture.Xunit2` for xUnit v2, which depends on `xunit.extensibility.core` in the range from 2.x up to, but not including, 3.0; - no package for xunit.v3. The contracts differ, so this is not a version-range quirk: | | xUnit v2 (`AutoFixture.Xunit2`) | xunit.v3 | |---|---|---| | Base type | `Xunit.Sdk.DataAttribute` | `Xunit.v3.DataAttribute` | | Data method | `GetData(MethodInfo)` returning `IEnumerable<object[]>` | `GetData(MethodInfo, DisposalTracker)` returning `ValueTask<IReadOnlyCollection<ITheoryDataRow>>` | `[AutoData]` and `[Frozen]` therefore cannot drive an xunit.v3 theory. ## Options when moving to xunit.v3 - **Use the fixture directly.** Create a `Fixture` with the same customizations in the test or in a small helper, and call `Freeze` and `Create` in the arrange step. This keeps every AutoFixture feature except the parameter injection. - **Stay on xUnit v2 for that project** until the suite can move, accepting that the rest of the solution may be on v3. - **Write a v3 data attribute** of your own, deriving from `Xunit.v3.DataAttribute`, that builds a fixture and returns one row; it is a small amount of code but it is yours to maintain, including `[Frozen]` ordering. Whichever you choose, decide before migrating the solution: a project that references both xUnit generations is the result of the migration stalling half-way, not a plan. ## Mistakes that show up in review - **The service first, the frozen mock last.** The setups then configure a mock the service never received, and the test either passes for the wrong reason or fails confusingly. - **Customizing inside the test body.** The parameters were created before the body ran; customizations belong in the derived attribute. - **`[InlineAutoData]` values in the wrong place.** The given values fill the first parameters, so put the fixed ones at the front. - **Reaching for the attribute's `Fixture` property.** It is `[Obsolete]` because it forces the lazily created fixture into existence; customizations belong in the factory passed to the constructor.

  • Why does [Frozen] on the last parameter have no effect on the service under test?
    Parameters are created left to right. When the service comes first, its constructor dependencies are created as fresh specimens; the later `[Frozen]` parameter is frozen only from then on, so the service holds a different instance. Put every `[Frozen]` parameter before the parameters that consume it.
  • Can you just reference AutoFixture.Xunit2 from an xunit.v3 project and keep [AutoData]?
    No. The package depends on xUnit v2's `xunit.extensibility.core` and its `AutoDataAttribute` implements v2's `Xunit.Sdk.DataAttribute` contract, which xunit.v3 does not use; v3 discovers data through `Xunit.v3.DataAttribute`. Use the fixture directly, keep that project on v2, or write a v3 attribute.

  • Put the service under test first and [Frozen] parameters after it.
  • AutoFixture.Xunit2 works unchanged in xunit.v3 because the attribute names match.
  • Customize [AutoData] with the AutoDataAttribute(Type fixtureType) constructor.
  • [Frozen] parameters may come in any order because AutoFixture resolves them first.
  • [InlineAutoData] values are assigned to the last parameters of the theory.

Assumes AutoFixture 4.18.1, whose AutoFixture.Xunit2 targets xUnit v2 (xunit.extensibility.core 2.x), and xunit.v3 4.0.1 on .NET 10, whose data attributes derive from Xunit.v3.DataAttribute.