This is something that’s been on the back burner for a while for me. I haven’t gotten around to trying it out until now. I just want to apologize up front for the code as images in this post, not proud of that but some circumstances led to that, sorry.
Moles is a isolation framework from MS Research (the almighty Peli de Helux, once Mr. MBUnit). It enables you to “mock” otherwise un-mockable objects like SPContext, SPWeb and so on.
Read more about it here: http://research.microsoft.com/en-us/projects/pex/
And this white paper: Unit Testing SharePoint Foundation with Microsoft Pex and Moles
Moles is distributed as a plug-in to Visual Studio, the 64-bit version (SharePoint 2010 is 64-bit only) can be download from this location: http://visualstudiogallery.msdn.microsoft.com/en-us/22c07bda-ffc9-479a-9766-bfd6ccacabd4
Install it in god old Next * n –> Finish manner.
Next step is to generate Moles from the Assemblies containing the classes you want to isolate/mock. Crack open your SharePoint project after you installed the plug-in. Expand your references and locate the reference that you want to generate Moles from, I chose Microsoft.SharePoint.Publishing in the image below, but as you can see I’ve already done it for Microsoft.SharePoint. Right-click it and select Add Moles Assembly.
Now Build your project and let’s have a look at what changes the Moles framework done to your project.
This next step is only valid if you’re using Team Foundation Server. In order for this to work on the TFS build server (anyway, the way we got it working), you need change the build action of the <Assembly name>.moles file from Moles to None.
And you’re set to go do some testing.
First off, let’s have a look at a method we want to get tested.
As we can see it takes a SPWeb object as a parameter and calls web.Site.RootWeb on it. (It passes this to the CountryRepository, but we don’t have to care about that here – it’s also mocked :)).
So we need to get our test started. Some initial points:
Next step is to set up behavior for the moles. Remember from above web.Site.RootWeb. so the first spweb returns an spsite that returns a spweb (RootWeb). Hooking up behaviors for properties is done by the original property name plus Get/Set. Hooking up the Site property on a SPWeb object hence becoms spweb.SiteGet. The image below illustrates this and how to build the command chain.
That done we can now call InitializeView with our Moled spweb and get a predictable controlled execution:
Now let’s look at the test as a whole. Worth noticing is that there is a few Moq mocks in this test also to isolate the thing I want tested.
Hope this post can lower the hurdle for some to get into unit testing your SharePoint code.