Share via


Walkthrough: Verify SharePoint Code by Using Unit Tests

Unit testing enables you to more accurately debug and check the operation of your code. This walkthrough demonstrates how to incorporate unit testing into a SharePoint application. While this walkthrough uses a specific SharePoint project type, any type of SharePoint code project can be tested by using unit testing.

Begin with a standard list definition project with a list instance and event receiver, and then add a unit test to the event receiver code that adds an announcement list to SharePoint. The creation of the announcement causes the event receiver to modify the announcement. The unit test checks to see whether the announcement was modified as expected and reports back the results.

This walkthrough illustrates the following tasks:

  • Creating a list definition with a list instance by using the List Definition project template.

  • Creating an event receiver by using the Event Receiver project template.

  • Adding and modifying list elements by using code.

  • Adding a unit test to a SharePoint project.

  • Running the unit test on a SharePoint project.

  • Viewing and interpreting the unit test results.

    Note

    Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Working with Settings.

Prerequisites

You need the following components to complete this walkthrough:

Creating a List Definition Project

First, create a list definition project with a list instance.

To create a List Definition Project

  1. Start Visual Studio 2010 by using the Run as Administrator option.

  2. On the File menu, point to New, and then click Project. The New Project dialog box appears.

  3. At the top of the New Project dialog box, select .NET Framework 3.5 in the drop-down list.

  4. In the New Project dialog box, expand the SharePoint node under the language that you want to use, and then select the 2010 node.

  5. In the Templates pane, select List Definition, and then click OK.

    The SharePoint Customization Wizard appears. Use the default project name, ListDefinitionProject1. This wizard enables you to select the site that you will use to debug the project and the trust level of the solution.

  6. Select Deploy as a farm solution, and then click Next. ALM features work only with farm solutions.

  7. In the Choose List Definition Settings window, click Finish to accept the default values. This creates an Announcements list definition and adds an instance of that list to SharePoint.

Adding an Event Receiver to the List Definition

Add an event receiver to the list definition to enable you to respond to changes made to the list definition.

To add an Event Receiver to the Project

  1. Click the list definition in Solution Explorer.

  2. On the Project menu, click Add New Item.

  3. In the Add New Item dialog box, in the Installed Templates pane, expand the SharePoint node, and then click 2010.

  4. In the list of SharePoint templates, select Event Receiver, and then click Add. Use the default project item name, EventReceiver1.

  5. In the Choose Event Receiver Settings window, leave the event receiver type as List Item Events and use the default event source.

  6. In the Handle the following events list, check An item is being added, and then click Finish. This creates an event handler that triggers when an announcement is created.

  7. Replace the ItemAdding method of the EventReceiver1 class with the following code.

    Public Overrides Sub ItemAdding(properties As SPItemEventProperties)
        properties.AfterProperties("Body") = "Note added by event receiver"
        MyBase.ItemAdding(properties)
    End Sub
    
    public override void ItemAdding(SPItemEventProperties properties)
    {
        properties.AfterProperties["Body"] = "Note added by event receiver"; 
        base.ItemAdding(properties);
    }
    
  8. Add a breakpoint on the properties.AfterProperties line. This is used later when testing the event receiver.

  9. Build the project.

Adding a Unit Test to the Event Receiver

To test whether the event receiver is operating properly, add a unit test to it.

To add a Unit Test to the Event Receiver

  1. On the Test menu, click New Test. The Add New Test dialog box appears.

  2. In Templates, click Unit Test Wizard.

  3. In the Add to Test Project dropdown list, select either Create a new Visual C# test project or Create a new Visual Basic test project, and then click OK. For this example, use the default test project name, TestProject1.

  4. The next window displays a tree view of the list definition project. Expand the nodes in the tree view until you see the ItemAdding method.

  5. Select the check box next to the ItemAdding method, and then click OK.

    This creates a new project named TestProject1 with a code module named EventReceiver1Test. The code module contains a method, ItemAddingTest, which is used to test the corresponding ItemAdding method.

  6. Highlight the test project in Solution Explorer and then click Property Pages on the View menu.

  7. In the Property Pages for the test project, click the Application tab, and then select .NET Framework 3.5 in the Target framework drop-down list.

    The Target Framework Change dialog box appears and asks whether you want to change the target framework. Click Yes. This ensures that the .NET Framework version used by the test project matches that used by the SharePoint project.

  8. Add the following code to the top of the EventReceiver1Test class.

    ' SharePoint site/subsite.
    Private siteUrl As String = "https://localhost"
    Private webUrl As String = "/"
    
    // SharePoint site/subsite.
    private string siteUrl = "https://localhost";
    private string webUrl = "/";
    
  9. Replace the ItemAddingTest method with the following code.

    <TestMethod()> _
    Public Sub ItemAddingTest()
        Try
            Using site As New SPSite(siteUrl)
                Using web As SPWeb = site.OpenWeb(webUrl)
                    ' Reference the list instance.
                    Dim mySite As SPList = web.Lists("ListDefinitionProject1 - ListInstance1")
    
                    ' Add a new announcement to the Announcements list.
                    Dim listItems As SPListItemCollection = mySite.Items
                    Dim item As SPListItem = listItems.Add()
                    item("Title") = "A Unit Test Announcement"
                    item("Expires") = "1/1/2099"
                    item.Update()
    
                    ' Test whether the event receiver added the text to the announcement.
                    Dim existingItem As SPListItem = listItems(0)
                    Assert.AreEqual(existingItem("Body").ToString().Contains("Note added by event receiver"), True, "Body passed!")
                End Using
    
            End Using
    
        Catch e As Exception
            Console.WriteLine("Error: " & e.ToString())
        End Try
    End Sub
    
    public void ItemAddingTest()
    {
        try
        {
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb(webUrl))
                {
                    // Reference the list instance.
                    SPList mySite = web.Lists["ListDefinitionProject1 - ListInstance1"];
    
                    // Add a new announcement to the Announcements list.
                    SPListItemCollection listItems = mySite.Items;
                    SPListItem item = listItems.Add();
                    item["Title"] = "A Unit Test Announcement";
                    item["Expires"] = "1/1/2099";
                    item.Update();
    
                    // Test whether the event receiver added the text to the announcement.
                    SPListItem existingItem = listItems[0];
                    Assert.AreEqual(existingItem["Body"].ToString().Contains("Note added by event receiver"), true, "Test succeeded!");                                               
                }
            }
    
        }
    
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
    }
    

    This code opens the SharePoint site and adds a new announcement. When the new announcement is added to SharePoint, the code in the event receiver triggers, adding a comment to the announcement. The code in the unit test checks to see whether the event receiver added the comment to the announcement by calling Assert.AreEqual.

  10. Select TestProject1 in Solution Explorer, point to Edit Test Settings on the Test menu, and then click Local (local.testsettings). The Test Settings window appears.

  11. In the left pane of the Test Settings window, click Hosts, and then select Run tests in 64 bit process on 64 bit machine in the Run tests in 32 bit or 64 bit process drop-down list. Click Apply, and then Close.

    This setting is necessary for testing SharePoint applications, which are 64-bit.

Deploy the Solution

After creating the SharePoint solution and unit test, deploy the SharePoint solution, and then change the startup project. The unit test requires the SharePoint project to be in place on the SharePoint server before testing, so you must deploy the SharePoint project. After deploying the project, change the startup project to the unit test to enable F5 debugging.

To Deploy the Solution

  1. Click Deploy Solution on the Build menu to deploy the SharePoint solution.

  2. Right-click TestProject1 and select Set as StartUp Project.

Run the Unit Test

Now that the SharePoint solution is in place and the unit test is ready, run the unit test to check whether the event receiver is working properly.

To Run the Unit Test

  1. Press F5 to run the test project.

    The test code creates a new announcement on the SharePoint site, triggering the event receiver.

  2. When the breakpoint is encountered, press F5 to continue.

    This line in the event receiver adds a comment to the new announcement. The test code then checks whether the comment exists in the announcement.

  3. The Test Results window appears and specifies that ItemAddingTest passed. Double-click ItemAddingTest in the list to view the test details.

    The test result details include information such as the name of the test, the starting and ending times, and the test duration.

See Also

Tasks

Walkthrough: Debug a SharePoint Application by Using IntelliTrace

Concepts

Anatomy of a Unit Test

Creating and Running Unit Tests for Existing Code

Debugging with IntelliTrace

Other Resources

Verifying and Debugging SharePoint Code by Using ALM Features