Unit Testing SharePoint projects with Microsoft Moles

SharePoint is very powerful development platform, but it’s hard to test your code without changing it. It widely uses sealed classes, non-virtual and static methods and static properties, which make it impossible to mock its objects via popular free mocking frameworks: Rhino Mocks, Moq or NMock. However there is one free framework exists on the market. It’s called Microsoft Moles Isolation Framework and it can be plugged into Visual Studio 2008/2010 Professional Edition.

To use Moles we need:
1) Download Moles x86 or x64 edition
2) Install it
3) Open your test project in Visual Studio
4) Add reference to Microsoft SharePoint library (and/or any other library you need) into your project
5) Select Microsoft.SharePoint in references list, open context menu and choose “Add Moles Assembly”


After this step a new file Microsoft.SharePoint.moles will be added to the project.

6) Run Build command of the project. After build we should see new references added to the project: Microsoft.Moles.Framework, Microsoft.SharePoint.Behaviors and Microsoft.SharePoint.Moles.

Now we can kick off with a test code. I created a very basic scenario for the sake of simplicity. The code that will be tested checks if the current user has a specific role:


And our test code will look like this:


In lines 62-67 we mock SPContext.Current and SPContext.Current.Web objects.
Now we need to mock SPContext.Current.Web.AllRolesForCurrentUser and role.Name. We can’t mock AllRolesForCurrentUser directly via SPWeb class because this property is contained in the parent class - SPSecurableObject, so here we use a Mole trick – wrapping child class SPWeb with its parent SPSecurableObject (line 69). And in 69-73 lines we bound a list of roles to AllRolesForCurrentUser and mocking its Name property. An attribute [HostType(“Moles”)] is required when a test method uses Moles. Now instead of calling real SPContext.Current a test runner calls our mocking code.

Unfortunately, Moles framework is not supported in Visual Studio 2012. Microsoft built a new generation of Moles called Microsoft Fakes which supported in Visual Studio 2012 but only in Ultimate Edition. In addition, there are commercial frameworks exist on the market: TypeMock and Teleric’s JustMock which cost $799 and $399 respectively for 1 single named user. So, SharePoint developers don’t have an excuse not to use TDD or write unit tests because they can’t change code of SharePoint or some other library J

Comments

Post a Comment

Popular posts from this blog

Client-side scripting for Taxonomy/Term Set Fields

SharePoint delegate control is rendered twice

Some thoughts on using Sitecore Habitat for Production codebase