This was a little tricky to figure out, and finding info on typemock is kind of hard sometimes, so here it is.
- Get a fake SPFarm object
SPFarm fakeFarm = Isolate.Fake.Instance<SPFarm>(Members.ReturnRecursiveFakes);
- Fake SPFarm.Local with the fake farm
Isolate.WhenCalled(() => SPFarm.Local).WillReturn(fakeFarm);
- Fake the fakeFarm.Properties with a Hashtable containing your fake properties
Hashtable farmProps = new Hashtable();
farmProps.Add("WindwardArrowLicense", testLicense);
Isolate.WhenCalled(() => fakeFarm.Properties).WillReturn(farmProps);
Here's an example test method.
[Test, Isolated]
public void ReadLicense_RequestExistingLicenseFromLicenseHandler_LicenseReturned()
{
// setup the fake farm
SPFarm fakeFarm = Isolate.Fake.Instance<SPFarm>(Members.ReturnRecursiveFakes);
// fake the "SPFarm.Local"
Isolate.WhenCalled(() => SPFarm.Local).WillReturn(fakeFarm);
// fake properties
Hashtable farmProps = new Hashtable();
farmProps.Add("WindwardArrowLicense", testLicense);
Isolate.WhenCalled(() => fakeFarm.Properties).WillReturn(farmProps);
string readLicense = ArrowLicenseHandler.ReadLicense();
Assert.AreEqual(testLicense, readLicense);
Isolate.Verify.WasCalledWithAnyArguments(() => fakeFarm.Properties);
}
Happy mocking!


Great post and wonderful to see people blogging about this - has been a long time passion of mine to get more people doing good unit testing in SharePoint.
A couple of tweaks for consideration:
Members.ReturnRecursiveFakes is the default, could leave out
Also someone bring really picky (not me :) ) you could suggest the line
Isolate.Verify.WasCalledWithExactArguments
You tests and code are already coupled due to the need for using Isolator.
Congrats on doing Unit Testing with SharePoint :)
Posted by: Andrew Woodward | 12/21/2011 at 12:26 AM
thanks for the info, Andrew
Posted by: meowkins | 01/13/2012 at 02:33 PM