logo

Auto-Mocking with FakeItEasy and AutoFixture

AutoFixture can become an auto-mocking container using Moq (described here) and Rhino Mocks (described here).

In addition to the above auto-mocking features it is now possible to use FakeItEasy.

To install AutoFixture with Auto Mocking using FakeItEasy, run the following command in the Package Manager Console:

PM> Install-Package AutoFixture.AutoFakeItEasy

To use it, add an AutoFakeItEasyCustomization to the Fixture instance:

var fixture = new Fixture()
    .Customize(new AutoFakeItEasyCustomization());

Here is a typical usage inside a test method which will automatically create mocked instances using FakeItEasy:

var fixture = new Fixture()
    .Customize(new AutoFakeItEasyCustomization());
var result = fixture.CreateAnonymous<IInterface>();

To explicitly use FakeItEasy inside a test you need to Freeze it first:

[Fact]
public void FixtureCanFreezeFake()
{
    // Fixture setup
    var fixture = new Fixture()
        .Customize(new AutoFakeItEasyCustomization());
    var dummy = new object();
    var fake = fixture.Freeze<Fake<IInterface>>();
    fake.CallsTo(x => x.MakeIt(dummy))
        .Returns(null);
    // Exercise system
    var result = fixture.CreateAnonymous<IInterface>();
    result.MakeIt(dummy);
    // Verify outcome
    A.CallTo(() => result.MakeIt(dummy)).MustHaveHappened();
    // Teardown
}

The above example can be made even more elegant by using AutoData theories:

[Theory, AutoFakeItEasyData]
public void FixtureCanFreezeFake([Frozen]Fake<IInterface> fake, IInterface sut)
{
    var dummy = new object();
    sut.MakeIt(dummy);
    A.CallTo(() => sut.MakeIt(dummy)).MustHaveHappened();
}

Update (2014/02/28): It is also possible to use the [Frozen] attribute on the IInterface directly, as Mark Seemann commented here.

Below is the code for the AutoFakeItEasyDataAttribute class:

public class AutoFakeItEasyDataAttribute : AutoDataAttribute
{
    public AutoFakeItEasyDataAttribute()
        : base(new Fixture().Customize(new AutoFakeItEasyCustomization()))
    {
    }
}

An automatically published release created from the latest successful build can also be downloaded from here.