Sample 2: Explicitly Faking an SPItem Collection
Original Method
The following sample shows a method that returns all of the items in a specific list:
C# public List<SPItems> GetUrgentTasks() { var site = new SPSite("http://sharepoint.typemock.com"); var taskList = site.OpenWeb().Lists[TASKS_LIST_NAME]; var urgentTasks = new List<SPItem>(); foreach (SPItem item in taskList.Items) { urgentTasks.Add(item); } return urgentTasks; }
VB
Public Function GetUrgentTasks() As List(Of String)
Dim site = New SPSite("http://sharepoint.typemock.com")
Dim taskList = site.OpenWeb().Lists(TASKS_LIST_NAME)
Dim urgentTasks = New List(Of String)()
For Each item As SPListItem In taskList.Items
If item(PriorityFieldName) IsNot Nothing AndAlso item(PriorityFieldName).ToString() = Priority.Urgent.ToString() Then
urgentTasks.Add(item.Name)
End If
Next
Return urgentTasks
End Function
Typemock Isolator Features Used
• Recursive Fakes
• Swap Future Instance
• Replacing Collections
Scenario
1. Fake the SPSite class. Because you need all of the object-model classes instantiated from SPSite to be faked as well, use the Recursive Fakes feature.
2. Create a fakeItem object.
3. Explicitly declare a collection of three fakeItem objects that will be returned when SPList.Items() is called.
4. Call the method and check the returned values.
Code
C# [TestMethod, Isolated] public void GetAllTasks_ThreeItemsInTasksList_ThreeTaskItemsFound() { // Fake recursively the next SPSite and all its nested classes are faked var fakeSite = Isolate.Fake.NextInstance<SPSite>(); // Retrieve a fake SPList to set behavior var fakeTaskList = fakeSite.OpenWeb().Lists[SharePointLogic var>.TASKS_LIST_NAME]; // Create a fake SPListItem var fakeItem = Isolate.Fake.Instance<SPListItem>(); // List collection shall return an array containing three fake items IsolateWillReturnCollectionValuesOf(new[] {fakeItem, fakeItem, fakeItem}); // Call the method under test var urgentTasks = classUnderTest.GetAllTasks(); Assert.AreEqual(3, urgentTasks.Count); }
VB
<TestMethod(), Isolated()>
Public Sub GetAllTasks_ThreeItemsInTasksList_ThreeTaskItemsFound()
' Fake recursively the next SPSite and all its nested classes are faked
Dim fakeSite = Isolate.Fake.NextInstance(Of SPSite)()
' Retrieve a fake SPList to set behavior
Dim fakeTaskList = fakeSite.OpenWeb().Lists(SharePointLogic.TASKS_LIST_NAME)
' Create a fake SPListItem
Dim fakeItem = Isolate.Fake.Instance(Of SPListItem)()
' List collection shell return three fake items// List collection shall return an array containing three fake items
Isolate.WhenCalled(Function() fakeTaskList.Items).WillReturnCollectionValuesOf(New SPListItem() {fakeItem, fakeItem, fakeItem})
' Call the method under test
Dim urgentTasks = SharePointLogic.GetAllTasks()
Assert.AreEqual(3, urgentTasks.Count)
End Sub