SharePoint Testing Base Class

I have created a base class library for testing SharePoint projects using unit tests, regression tests, integration tests and automated browser tests. It uses the two third-party applications TypeMock Isolator for SharePoint and WatIN.

As an example, if a web part calls the SPContext as:

   1: /// <summary>


   2: /// Primitive sample of web part using the <see cref="SPContext"/> object.


   3: /// </summary>


   4: /// <param name="writer">The <see cref="HtmlTextWriter"/> to write the output to.</param>


   5: protected override void Render(HtmlTextWriter writer)


   6: {


   7:     writer.Write("<h1>" + SPContext.Current.Site.RootWeb.Title + "</h1>");


   8: }




We can now mock this either by making the whole SPContext fake or by ensuring that the SPContext talks to a site collection that we have instantiated programmatically.





   1: /// <summary>


   2: /// Ensure that the <see cref="Microsoft.SharePoint.WebPartPages.WebPart"/> can render stand-alone.


   3: /// </summary>


   4: [Test]


   5: [Isolated]


   6: public void TestRenderUnit()


   7: {


   8:     SPContext context = Mock.MockSharePointContext();


   9:     Isolate.WhenCalled(() => context.Site.RootWeb.Title).WillReturn("Fake");


  10:     Assert.IsTrue(RenderToString(webPart).Contains("<h1>Fake</h1>"));


  11: }


  12:  


  13: /// <summary>


  14: /// Ensure that the <see cref="Microsoft.SharePoint.WebPartPages.WebPart"/> can render when attached to SharePoint API.


  15: /// </summary>


  16: [Test]


  17: [Isolated]


  18: public void TestRenderIntegration()


  19: {


  20:     Mock.MockSharePointContext(Web);


  21:     string evidence = "<h1>" + Site.RootWeb.Title + "</h1>";


  22:     Assert.IsTrue(RenderToString(webPart).Contains(evidence));


  23: }




Download the code, documentation and examples.

0 comments: