Fake Everything You Don’t Care About

Isn’t that what mock frameworks do? Yes. But.

In order to make our tests pass, we need to isolate everything our test pass through. This means ignoring void calls, and return values on methods in order for our test to keep running. And not crash in the middle.

So assuming we landed a big hunk of code we need to test, we start specifying behaviors left and right. Ignore this, return a not-null object. Just to test a very specific piece of code. But do we need to actually write this code? Can’t we just ignore anything we don’t care about?

Recursive fakes do just that. It starts with a root object. This object has all kind of methods and properties that return values. Any returned object from these methods also has methods and properties, and so on. In one short line of code, I can ignore any calls on children objects, and return fake objects from their methods.

For example: In this method, there’s a chain of calls, which basically are method calls on children objects:

public void SignOut()
{
   HttpContext current = HttpContext.Current;
   HttpSessionState session = current.Session;
   session.Abandon();
}

To ignore everything, along with calls to children, I’d do this:

Isolate.Fake.StaticMethods<HttpContext>(Members.ReturnRecursiveFakes);

That’s it. No need to set any other behaviors. All calls in SignOut will be faked, and no NullReferenceException in sight.

Here’s a twist for you. Let’s say I want to return the item count in a session. This time we need to return a value on this:

HttpContext.Current.Session.Count

Even without declaring a fake on HttpContext, I can do this:

Isolate.WhenCalled(() => HttpContext.Current.Session.Count).WillReturn(5);

That’s easy enough. But I can also do this:

Isolate.Fake.StaticMethods<HttpContext>(Members.ReturnRecursiveFakes);
HttpSessionState fakeSession = HttpContext.Current.Session;
Isolate.WhenCalled(()=>fakeSession.Count).WillReturn(5);

Since HttpContext is now recursively faked, I can just grab the fake Session from the object tree and set behavior (or verify) on it. This is not intuitive at first, but in the long run makes tests more readable.

This technique is great for object models. Just grab the main object, slap a recursive fake on it, and focus on what you really need to test.

Note that you can click the link to learn more on Unit Testing. Or click the following link to learn how to unit test a Microsoft SharePoint application.

Want to start unit testing? Take advantage of our 30-day FREE trial of Isolator Complete. Get it now

Technorati Tag:
.Net , Visual Studio , Microsoft , Agile ,Test Driven Development ,Mock

  • Soon Hui

    Thanks, Gil!

    Just clear up my concerns and questions..

TOP