Follow @RoyOsherove on Twitter

Isolator feature focus: Recursive Fakes

Here’s another feature Typemock Isolator has that no one else currently has: the ability to return fake objects from properties recursively (without the use of an auto mocking container for such a feat). this saved a lot of reperitive test code of creating stubs that return stubs that return some custom result.

For example, an object person has a manager which is also a person (which of course also has a manager etc..)

here’s how you can use this feature:

[Test,Isolated]
public void test()
{
    Person person = Isolate.Fake.Instance<Person>(Members.ReturnRecursiveFakes);
    Assert.IsNotNull(person.Manager.Manager.Manager.Manager);
}

This test will pass (Manager is null by default. look at the class in question below:

class Person
   {
       public string Name
       {
           get { return name; }
       }

       public Person Manager
       {
           get { return manager; }
       }

       private string name;
       private Person manager;
   }

 

Here is how you can return stub results from properties of the stubbed objects:

[Test,Isolated]
public void test()
{
    Person person = Isolate.Fake.Instance<Person>(Members.ReturnRecursiveFakes);
    Isolate.WhenCalled(() => person.Manager.Manager.Name)
               .WillReturn("roy");

    Assert.AreEqual("roy",person.Manager.Manager.Name);
}

 

Notice that:

  • By saying “ReturnRecursiveFakes” we are actually saying “I don’t care who uses this object and how from now on. It will return a fake when needed from all properties and the properties of the stubs as well.

  • We can still set stub results on the fakes on any level

 

If we wanted to only fake the Manager name and leave everything else intact we could just use a live object in the test like this:

 

[Test,Isolated]
public void test()
{
    Person person = new Person();

    Isolate.WhenCalled(() => person.Manager.Manager.Name)
               .WillReturn("roy");
    Assert.AreEqual("roy",person.Manager.Manager.Name);
}

Deadlock Challenge

BDD: Behavior vs. Spec Frameworks