Mocking Sharepoint for Testing
In my previous post I talked about using Isolator to mock Sharepoint to aid the speed of the development process. I find this a productive way of working, but it does not really help in the realm of automated testing. You need a way to programmatically explore a webpart, preferably outside of SharePoint to check its correctness.
You could use the methods in my previous post and some form of automated web test, but this does mean you need to spin up a web server of some descriptions (IIS, Cassini etc. and deploy to it) An alternative is look at the Typmock addin Ivonna. This a creates a fake web server to load you page and tools to explore it.
I will describe how to use this technique using the same example as my previous post.
Previously I had placed all the code to fake out SharePoint in the Page_Load event of the test harness page. As I am now trying to write an unit/integration test I think it better to move this into the test itself so I would delete code I placed in the Page_Load event other than any property settings on the actual webpart. I would actually refactor the lines creating the fake URL context and fake SPSite into some helper methods and then call them from my new test. I would then load the page in Ivonna and check it’s values.
I have tried to show this below, using a couple of techniques to show how to get to components in the page.
1: [TestMethod, Isolated]
2: public void LoadWebPage_SpSimpleWebPart_3EntriesInList()
4: // Arrange
8: TestSession session = new TestSession(); //Start each test with this
9: WebRequest request = new WebRequest("/SpSimpleTest.aspx"); //Create a WebRequest object
11: // Act
12: WebResponse response = session.ProcessRequest(request); //Process the request
14: // Assert
15: //Check the page loaded
18: // the the Ivonna extension method to find the control
19: var wp = response.Page.FindRecursive<DemoWebParts.SpSimpleWebPart>("wp1");
22: // so we have to use the following structure and dig knowing the format
23: // webpart/table/row/cell/control
24: var label = ((TableRow)wp.Controls.Controls).Cells.Controls as Label;
28: var list = ((TableRow)wp.Controls.Controls).Cells.Controls as DropDownList;
30: Assert.AreEqual(3, list.Items.Count);
Now I have to say I had high hopes for this technique, but it has not been as useful as I would hope. I suspect that this is due to the rapid changing of the UI design of client’s webparts making these tests too brittle. We have found the ‘mark 1 eyeball’ more appropriate in many cases, as is so often true for UI testing.
However, I do see this as being a great option for smoke testing in long running projects with fairly stable designs.
Read the complete post at http://blogs.blackmarble.co.uk/blogs/rfennell/archive/2010/04/22/mocking-sharepoint-for-testing.aspx