Using Typemock Isolator for Integration Tests

Yeah, I know. Typemock Isolator is great for unit testing against API’s that are hard to mock, but this last iteration, I found a new use for Typemock Isolator.

I worked with our test team to develop a set of integration tests that are run by MSTest and simulate running our components in the context of a specific web app. Usually in SharePoint, this is done as “over the glass” tests that exercise the components app via some UI because it is difficult to setup the appropriate SFarm/SPWebApplication/SPSite/SPWeb environment for integration tests. This is especially difficult if the code you are testing internally access SPFarm.Local or SPContext.Current.

Let’s assume you have already constructed an SFarm/SPWebApplication/SPSite/SPWeb environment. The trick now is to direct calls to SPFarm.Local and SPContext.Current to your environment. This is where Typemock Isolator comes in.

 using(SPSite spSite = new SPSite("[URL to integration test SPSite instance]")
{
    SPContext spContext = SPContext.GetContext(spSite);
    Isolate.WhenCalled(()=>SPContext.Current).WillReturn(spContext);

    //Arrange
    //Act
    //Assert
}

The preceding code illustrates how you can redirect calls to SPContext.Current to an SPContext of your chosing. You can also redirect calls to SPFarm.Local using the following code:

 using(SPSite spSite = new SPSite("[URL to integration test SPSite instance]")
{
    
    Isolate.WhenCalled(()=>SPFarm.Local).WillReturn(spSite.WebApplication.Farm);

    //Arrange
    //Act
    //Assert
}

This is necessary if the SFarm/SPWebApplication/SPSite/SPWeb environment is not on the same box that is running the integration tests.