Recursive Mocking

Recursive mocking feature allows you to automatically create fakes from interfaces declared as return values of methods, properties or indexers.

Consider the following example. Suppose that we have a class SystemUnderTest and several dependent on each other interfaces:

public class SystemUnderTest
{
    private readonly IOutterInterface _outterInterface;

    public SystemUnderTest(IOutterInterface outterInterface)
    {
        if (outterInterface == null)
            throw new ArgumentNullException();

        _outterInterface = outterInterface;
    }

    public int Execute()
    {
        var bar = _outterInterface.Foo.GetBar();
        return bar.Execute();
    }
}

public interface IOutterInterface
{
    IFoo Foo { get; set; }
}

public interface IFoo
{
    IBar GetBar();
}

public interface IBar
{
    int Execute();
}

Assume that we need to test the behavior of SystemUnderTest.Execute() method , which must return a specific error code in our test case. Depending upon recursive mocking we can write unit test in such a way:

[Test]
[TrueFake]
public void Execute_ExecuteWithError_ReturnsErrorCode()
{
    // Arrange.
    const int expectedErrorCode = 255;
    var outterInterfaceFake = TrueFake.Of<IOutterInterface>();
    Arrange.Call(() => outterInterfaceFake.Foo.GetBar().Execute()).Returns(expectedErrorCode);

    // Act.
    var sut = new SystemUnderTest(outterInterfaceFake);
    var actualErrorCode = sut.Execute();

    // Assert.
    Assert.AreEqual(expectedErrorCode, actualErrorCode);
}

In this test, we do not need to instantiate additional fake-objects from IFoo and IBar interfaces and to pollute this unit test with additional code - True Fakes generates them automatically, and making code is more maintainable and readable.