Behaviors

Control recursion, constructor choice, and specimen policies with behaviors and attributes.

Behaviors change how AutoFixture handles edge cases like circular graphs and multi-constructor types.

Example scenario

You have a TreeNode type where each node references a parent, causing circular graphs. You also have MultiCtorProduct with both a parameterless and a greedy constructor — and you need to pick which one AutoFixture uses in xUnit.net 3 or NUnit 4 theories.

Example

Recursion — default ThrowingRecursionBehavior throws on circular graphs:

var fixture = new Fixture();

Assert.ThrowsAny<ObjectCreationException>(() => fixture.Create<TreeNode>());

Switch to OmitOnRecursionBehavior to omit recursive properties instead. See Circular references.

Modest and Greedy

Pick constructor greediness per parameter in theories (same attributes exist for xUnit.net 3 and NUnit 4):

[Theory, AutoData]
public void ModestAttribute_UsesParameterlessConstructor([Modest] MultiCtorProduct product)
{
    Assert.Equal("default", product.Name);
    Assert.Equal(0m, product.Price);
}

[Theory, AutoData]
public void GreedyAttribute_UsesFullestConstructor([Greedy] MultiCtorProduct product)
{
    Assert.False(string.IsNullOrEmpty(product.Name));
    Assert.NotEqual(0m, product.Price);
}

How it works

  • Behaviors — global policies on the fixture (recursion, omitting properties, etc.)
  • Modest — prefers the constructor with fewest parameters
  • Greedy — prefers the constructor with most parameters

Requires xUnit.net 3 or NUnit 4 for Modest and Greedy attributes.

Next steps

API