Unit testing Solution for Sharepoint – Typemock Isolator
| Looking for a low-cost solution for SharePoint testing?
Typemock Isolator for SharePoint makes it easy to test your web parts or any other SharePoint components (including support for SharePoint 2010). Isolator for SharePoint’s low cost means you can start testing your SharePoint applications now, and when you’re ready, you can upgrade to the full Isolator.
The problem with unit testing SharePoint In order to test SharePoint code, you need to perform long operations like retracting and deploying just to get ready to test. In this sort of the environment, unit tests’ greatest value – immediate feedback – gets lost, and therefore the developers are discouraged from doing unit testing. Typemock Isolator’s solution
public class MailboxWebPart : WebPart
{
private Label lblNewMessages;
protected void CreateChildControls(int i)
{
CreateChildControls();
}
protected override void CreateChildControls()
{
lblNewMessages = new Label();
lblNewMessages.Text = GetMessageNumberText();
this.Controls.Add(lblNewMessages);
base.CreateChildControls();
}
private string GetMessageNumberText()
{
// Open the site
using (SPSite site = new SPSite("http://www.nosuchsite.com"))
{
using (SPWeb web = site.OpenWeb())
{
SPList messages = web.Lists["Messages"];
// Check the message count and return the correct text
int numberOfItems = messages.ItemCount;
if (numberOfItems == 0)
{
return "No new messages.";
}
else
{
return "New messages: " + numberOfItems;
}
}
}
}
}
Our main logic is the GetMessageNumberText method. However, there are a number of problems with testing: Let’s see how we can easily and quickly test it with Isolator: [TestMethod]
public void GetMessageNumberText_ZeroMessages_NoNewMessagesText()
{
// Fake the site
SPSite fakeSite = Isolate.Fake.Instance<SPSite>();
Isolate.Swap.NextInstance<SPSite>().With(fakeSite);
// Simulate Zero messages in the SharePoint database
Isolate.WhenCalled(() =>
fakeSite.OpenWeb().Lists["Messages"].ItemCount)
.WillReturn(0);
// Invoke the private method we want to test
MailboxWebPart webPart = new MailboxWebPart();
string result = (string) Isolate.Invoke.Method(webPart, "GetMessageNumberText");
// Chect the returned text
Assert.AreEqual("No new messages.", result);
}
Note that we don’t need SharePoint running or even installed: we just need the SharePoint DLLs to compile the tests. We fake the entire SharePoint object set with just a few lines (even the SPSite object), invoke the private method with a short API and test the result. Download a free trial of Typemock’s SharePoint Unit Testing tool to start writing your own SharePoint tests or click through our resources below for all the information and support you need to effectively unit test in SharePoint. Download Typemock Isolator SharePoint Unit Testing Tool! |