Faking Instances of Objects

Fake object creation
Fake objects are objects that replace real objects in the code under test. Fake objects behavior can be set up using Isolate.WhenCalled() and verified using Isolate.Verify.

Fake objects replace Mock and MockObject in the AAA API.

Creating fake objects is done by using the Isolate.Fake.Instance() method. This example shows basic fake object creation:
RealLogger fake = Isolate.Fake.Instance<RealLogger>();
Fake object behaviors
Fake objects can be created with a few predefined behaviors. These behavior types will set the default behavior for the created fake object. Later you can replace specific method behavior by using Isolate.WhenCalled(). The  fake object behavior types are defined by passing a Members enum parameter to Isolate.Fake.Instance(). The possible behavior types are:
Members.ReturnRecursiveFakes is the default fake object behavior. This means that calling Isolate.Fake.Instance() is the same as passing in Members.ReturnRecursiveFakes.
Recursive fake objects
Creating fake objects with Members.ReturnRecursiveFakes creates a powerful and versatile faking tool. If the code under test calls an intricate object model that is replaced by this fake object, deep calls (chained calls several levels down the object model) will be faked automatically. This saves the test author from faking return values and defining behavior for each hierarchy level explicitly.
The following example shows using recursive fake objects in order to fake a deep call. The fake RealLogger we create calls GetSon() which in turn returns another Son object on which another call is made:
[TestMethod]
[Isolated]
public void RecursiveStubWithExpectationOnSecondLevel ()
{
    // Arrange
    RealLogger fake = Isolate.Fake.Instance<RealLogger>(Members.ReturnRecursiveFakes);
    Isolate.WhenCalled(() => fake.GetSon().DoSomething()).WillReturn(10);

    // Act
    Logger son = fake.GetSon();
    son.DoSomething();

    // Assert
    Isolate.Verify.WasCalledWithAnyArguments(() => fake.GetSon().DoSomething());
}

See Also

Copyright © Typemock Ltd. 2004-2010. All Rights Reserved.