Home

AutoFixture

AutoFixture is a .NET library designed to simplify the process of creating test data for unit tests. It helps automate the generation of object graphs and eliminates the need for manual setup of test objects, making your tests cleaner and easier to maintain.

Summary

AutoFixture is a powerful tool that streamlines the process of creating test data in .NET applications. By automating object creation and allowing for easy customization, it helps improve the readability and maintainability of your unit tests. This makes it a valuable addition to any testing strategy within a .NET development environment.

Installation

dotnet add package AutoFixture

Example

Create a Sample Class

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Test:

using AutoFixture;
using Xunit;

public class PersonTests
{
    private readonly IFixture _fixture;

    public PersonTests()
    {
        _fixture = new Fixture(); // Create a new instance of Fixture
    }

    [Fact]
    public void Person_ShouldHaveNameAndAge_WhenCreated()
    {
        // Arrange
        var person = _fixture.Create<Person>(); // Automatically create a Person object

        // Act & Assert
        person.Should().NotBeNull();
        person.Name.Should().NotBeNullOrWhiteSpace();
        person.Age.Should().BeGreaterThan(0);
    }
}

You can also customize how AutoFixture creates objects:

[Fact]
public void Person_ShouldHaveSpecificAge_WhenConfigured()
{
    // Arrange
    var person = _fixture.Build<Person>()
                         .With(p => p.Age, 30) // Set specific value for Age
                         .Create();

    // Act & Assert
    person.Age.Should().Be(30);
}