SuperAPI AI Directory

dotnet-testing-autofixture-basics

Testing & quality

View repository

Updated 10-15 23:45

About this skill

AutoFixture Basics: Automatically Generating Test Data

Installing Packages

<PackageReference Include="AutoFixture" Version="4.18.1" />
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />

Or install via the command line:

dotnet add package AutoFixture
dotnet add package AutoFixture.Xunit2

Core API Summary

API Purpose Default Behavior
fixture.Create<T>() Generate a single object Automatically populate all properties
fixture.CreateMany<T>() Generate a collection 3 elements by default
fixture.Build<T>() Precisely control properties Use with With/Without
OmitAutoProperties() Set only required properties Leave the rest at default values

Basic Usage

Fixture is the core class that provides the ability to automatically generate test data:

  • Primitive types:int(random positive integer),string(GUID format),decimal、bool、DateTime、Guid
  • Complex objects: automatically constructs nested objects and collection properties; properties at all levels are automatically populated with values
  • Collection generation:CreateMany<T>() generates 3 elements by default; you can specify the count, e.g. CreateMany<T>(10)

For complete code examples, refer to references/basic-usage-examples.md

Precise Control with Build()

When you need to control specific properties, use the Build<T>() pattern:

Method Purpose Example
.With(prop, value) Specify a fixed value .With(x => x.Name, "測試客戶")
.With(prop, factory) Use a factory method to generate a value .With(x => x.Price, () => random.Next())
.Without(prop) Exclude a property, keeping its default value .Without(x => x.InternalId)
.OmitAutoProperties() Do not automatically set any properties Set only the properties you care about

Circular Reference Handling

When an object contains a circular reference (such as a Category's Parent property pointing to itself), AutoFixture throws by default ObjectCreationException。

Solution: Use OmitOnRecursionBehavior, remove the default ThrowingRecursionBehavior and add behavior to ignore circular references.

Recommendation: Create a AutoFixtureTestBase base class to handle circular references uniformly, avoiding repeated configuration in every test.

For complete code examples, refer to references/build-and-customization.md

xUnit Integration

Fixture Sharing and Customization

Use in the test class constructor Customize<T>() to set up shared data generation rules; all test methods share the same Fixture configuration.

Combining with Theory Tests

Together with [Theory] + [InlineData], use Build<T>().With() to set key property values for different input scenarios and verify the expected behavior of each scenario.

Anonymous Testing Principles

Tests should focus on "behavior" rather than "data":

  • Good practice: Use fixture.Create<T>() to generate arbitrary valid data and verify the operation result
  • Avoid: Relying on the specific content of randomly generated values (such as assuming age is greater than 18)
  • Correct: Use Build<T>().With() to explicitly set the key values that affect the test result

For complete code examples, refer to references/xunit-integration-examples.md

Evolution Comparison: Test Data Builder vs AutoFixture

Aspect Test Data Builder AutoFixture
Lines of code 40+ lines Builder + test 5-line test
Maintenance cost Object changes require updating the Builder Automatically adapts to changes
Development time Write the Builder first, then write the test Write the test directly
Large amounts of data Requires loops CreateMany(100)
Readability Clear business semantics Requires understanding AutoFixture

For the complete comparison code and hybrid strategy, please refer to references/xunit-integration-examples.md

Hybrid strategy recommendations

Combine the advantages of Test Data Builder and AutoFixture:

  • Use AutoFixture to create base data, then process it with a Builder
  • Use TestDataFactory to encapsulate commonly used data generation patterns
  • Use CreateMany<T>(count)

For the complete comparison code and hybrid strategy, please refer to references/xunit-integration-examples.md

Practical application scenarios

AutoFixture is commonly used in practice in the following scenarios:

  • Entity testing: paired with Theory to verify different input scenarios
  • DTO validation: use Build<T>() to generate data that conforms to validation rules
  • Large-scale data testing: use CreateMany() to generate batch data
  • Service layer testing: paired with NSubstitute to automatically generate Mock parameters

For complete code examples, please refer to references/practical-scenarios.md

Frequently asked questions

Q1: When should AutoFixture be used, and when should fixed values be used?

  • Use AutoFixture: for "filler" data that does not affect test results, such as a user's Email, address, etc.
  • Use fixed values: for "key" data that affects test logic, such as customer type in discount calculations or age value in age validation

Q2: How many does CreateMany generate by default? How can it be adjusted?

By default, 3 elements are generated; the number can be specified via a parameter:fixture.CreateMany<T>(10). To adjust globally, use fixture.RepeatCount = 5。

Q3: The string format generated by AutoFixture does not meet requirements?

Use Build<T>().With() to specify the format, or pair it with Customize<T>() to set global rules. If realistic data is needed, consider integrating Bogus.

Best practices

Should do

  1. Use the anonymous testing concept — focus on test logic rather than specific data
  2. Fix specific values only when necessary — use Build<T>().With() to set key properties
  3. Create a shared base class — uniformly handle common configurations such as circular references
  4. Reasonable collection size — adjust the CreateMany() count according to the test purpose

Should avoid

  1. Over-reliance on random values — do not assume the specific contents of random values
  2. Ignoring boundary values — boundary cases still need to be tested explicitly
  3. Abusing automatic generation — simple tests may be clearer with fixed values

Code templates

Please refer to the example files in the templates folder:

Output format

  • Generate a test class (.cs file) that uses AutoFixture
  • Include usage examples of Fixture.Create/CreateMany/Build
  • Provide .csproj package references (AutoFixture, AutoFixture.Xunit2)
  • Include circular reference handling and custom behavior configuration

Reference Resources

Original Article

Official Documentation

Related Skills

  • dotnet-testing-autofixture-customization - AutoFixture Advanced Customization
  • dotnet-testing-autofixture-bogus-integration - AutoFixture + Bogus Integration
  • dotnet-testing-autofixture-nsubstitute-integration - AutoFixture + NSubstitute Integration
  • dotnet-testing-autodata-xunit-integration - AutoData and xUnit Integration
  • dotnet-testing-test-data-builder-pattern - Test Data Builder Pattern