Pex & Moles with SharePoint – A Quick Example

I recently demoed moles against the SharePoint 2007 object model. I demoed testing a contrived method that simple returned true if the number of items in a SharePoint list was greater than 20. Code is below…

 

private const int ItemsPerPage = 10;

public bool ShowPagination()
{
    using (SPSite siteCollection = new SPSite(“
http://example.local”))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            SPList list = web.Lists[“MyList”];

            if (list.ItemCount > ItemsPerPage)
            {
                return true;
            }
        }
    }

    return false;
}

This is a difficult method to test, as you cannot mock out the SharePoint OM code (as it’s not written to an interface etc). As you are tied to SharePoint, you would need to alter the SharePoint list to test boundary conditions. This is where moles come in…

I generated a mole dll against the Microsoft.SharePoint dll in my test project, and was then able to intercept SharePoint OM calls via lambdas. The example below illustrates a test that force the value of the list.ItemCount to return a known value. Note that in my test, the SharePoint OM was not called, instead only the Mole classes were called (via a detour).

[TestMethod]
[HostType(“Moles”)]
public void ShowPaginationReturnsFalseWhenLessThanTenItems()
{
    // Arrange

    // Use initilizers and lamdba functions to set up moles
    // Only “mole” functionality that is used by code
    MSPSite.ConstructorString = (site, url) => new MSPSite(site)
    {
        OpenWeb = () => new MSPWeb
        {
            ListsGet = () => new MSPListCollection
            {
                ItemGetString = id => new MSPList
                {
                    ItemCountGet = () => 9
                }
            },
            Dispose = () => { }
        },

        Dispose = () => { }
    };

    // Act
    TableLogic tableLogic = new TableLogic();
    bool showPagination = tableLogic.ShowPagination();

    // Assert
    Assert.IsTrue(showPagination == false, “The page will be paginated”);
}

 

http://research.microsoft.com/en-us/projects/pex/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>