Search The Blog
About this site

@RoyOsherove

Subscribe!

This site aims to connect all the dots of my online activities - from tools, books blogs and twitter accounts, to upcoming conferences, engagements and user group talks.

from 5whys.com
Twitter: @RoyOsherove
My Book: The Art of Unit Testing
Latest Posts
« Deadlock Challenge | Main | BDD: Behavior vs. Spec Frameworks »
Saturday
Oct042008

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);
}

PrintView Printer Friendly Version

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>