Introduction
AutoFixture creates anonymous test data so you write less arrange code in unit tests.
AutoFixture helps you write unit tests with less hand-written setup. A fixture creates anonymous values during the arrange phase — strings, nested objects, and the system under test (SUT) — so you can focus on behavior instead of inventing test data.
In this tutorial
Work through these topics in order:
- Introduction — you are here
- Installation — add the NuGet package and verify restore
- Your first test — use
Fixture.Createin a unit test - Refactoring a test — shrink messy service arrange with AutoMoq and
Build
Example scenario
You are testing a ShippingLabelFormatter that builds a multi-line label from a customer. The test should verify that the label includes the customer's name and city. You do not care about specific values like "Jane Doe" or "Copenhagen" — any valid customer is fine.
Example
var fixture = new Fixture();
var customer = fixture.Create<Customer>();
var sut = fixture.Create<ShippingLabelFormatter>();
var label = sut.Format(customer);
Assert.Contains(customer.Name, label);
Assert.Contains(customer.Address.City, label);
How it works
new Fixture()— starts the data generator for this testCreate<Customer>()— builds aCustomerwith an anonymous name and nestedAddressCreate<ShippingLabelFormatter>()— creates the SUT without a manualnew- The asserts read from the object graph AutoFixture created, not from hard-coded strings
When constructors or dependencies change, you often change less arrange code than with hand-built objects.
Example types
The test above uses these types:
public class Address
{
public string Street { get; set; } = string.Empty;
public string City { get; set; } = string.Empty;
}
public sealed class Customer(string name, Address address)
{
public string Name { get; } = name;
public Address Address { get; } = address;
}
public sealed class ShippingLabelFormatter
{
public string Format(Customer customer) =>
$"{customer.Name}\n{customer.Address.Street}\n{customer.Address.City}";
}