“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
How to unit test your SharePoint custom code by isolating the object model (SPSite)
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:
1 2 3 4 5 6 7 8 9 10 11 |
public List GetUrgentTasks() { var site = new SPSite("https://www.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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
[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); } |
Learn more:
- Browse the SharePoint examples installed with Isolator.
All Programs->Typemock->Isolator ->Examples->Typemock.Examples.SharePoint.sln - See online documentation example
- Watch a 35 minute Webinar Recording on How to unit test SharePoint WebParts and User Administration Code
- Learn about Isolator for Sharepoint
- Use Typmeock to speed the development of Sharepoint Web Parts
Articles how others are using Isolator to test SharePoint Code:
- Developer testing of Sharepoint Web parts using Typemock Isolator and Ivonna
- Typemock Isolator and SharePoint testing