Which way to fake an item in Typemock

I raised a question on the Typemock forum concerning a problem I was having mocking Sharepoint SPFarm objects. It was all down to which way to fake items using the various techniques in Isolator. It was interesting enough, I thought, to repeat here as a blog post.

I had written some tests for a method that got a list of SiteCollections that a user had rights to access. The key point being the need to access the static property SPFarm.Local to get a list of Sharepoint services to iterate across. If I ran each test by itself it worked; but if run as a batch in TestDriven.Net or MSTest the first passed and the rest failed.

The problem was down to how I was creating the fake SPfarm, I was using:

SPFarm fakeFarm = Isolate.Fake.Instance(Members.ReturnRecursiveFakes);
Isolate.Swap.NextInstance().With(fakeFarm);

when I should have used

SPFarm fakeFarm = Isolate.Fake.Instance(Members.ReturnRecursiveFakes);
Isolate.WhenCalled(() => SPFarm.Local).WillReturn(fakeFarm);

Ok, I used the wrong call, but wait a minute, each of my tests were marked with the [Isolated] attribute. My understanding was this meant the Typemock system was reset between each test, and as I only call SPFarm.Local once per test were these two forms not equivalent?

This is the answer from Doron at Typemock, hope it clear up any confusion of the type I was suffering from.....

You are right in that the Isolate attribute resets fake behavior between each and every test. However, SwapNextInstance is triggered if and only if a constructor for T has been called. It is not equivalent to WhenCalled() but rather complementing.
Generally speaking, you set behaviors on your fake object (or static methods) using WhenCalled() and then you can choose how to inject that fake behaviour to the code under test:
- If the code under test receives a reference to the fake behavior, you just pass it in.
- If the code under tests receives it from a third party, you fake that third party to return the fake object you set up.
- If the code under test uses 'new' to instantiate the dependent behavior, use SwapNextInstance to replace the next 'new' with the faked object