“Typemock Isolator is a great way to open up the world of unit testing
to SharePoint developers. Unit testing SharePoint applications is an
important part of our soon to be released P&P SharePoint Guidance
and Typemock Isolator is integral to our unit testing guidance.”
Ajoy Krishnamoorthy, Lead Product Planner for Patterns & Practices,Developer Division at Microsoft
The biggest problem with testing SharePoint code, is its dependency on the SharePoint object model. The following example shows how to easily unit test your custom code. Here's the method we want to test:
public List GetUrgentTasks()
{
var site = new SPSite("http://sharepoint.typemock.com");
var taskList = site.OpenWeb().Lists[TASKS_LIST_NAME];
var urgentTasks = new List();
foreach (SPItem item in taskList.Items)
{
urgentTasks.Add(item);
}
return urgentTasks;
}
Here's how the test looks like:
[TestMethod]
[Isolated]
public void GetAllTasks_ThreeItemsInTasksList_ThreeTaskItemsFound()
{
// Recursive fake - complete SPSite object model is faked
var fakeSite = Isolate.Fake.Instance();
// Swap future instance of SPSite
Isolate.Swap.NextInstance().With(fakeSite);
// Retrieve a fake SPList to set behavior
var fakeTaskList = fakeSite.OpenWeb().Lists[TASKS_LIST_NAME];
// Create a fake SPListItem
var fakeItem = Isolate.Fake.Instance();
// List collection shall return an array containing three fake items
Isolate.WhenCalled(()=>fakeTaskList.Items).WillReturnCollectionValuesOf
(new[] {fakeItem, fakeItem, fakeItem});
// Call the method under test
var urgentTasks = classUnderTest.GetAllTasks();
Assert.AreEqual(3, urgentTasks.Count);
}