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()
3: {
4: // Arrange
5: TestHelpers.CreateFakeSPSite();
6: TestHelpers.CreateFakeURL();
7:
8: TestSession session = new TestSession(); //Start each test with this
9: WebRequest request = new WebRequest("/SpSimpleTest.aspx"); //Create a WebRequest object
10:
11: // Act
12: WebResponse response = session.ProcessRequest(request); //Process the request
13:
14: // Assert
15: //Check the page loaded
16: Assert.IsNotNull(response.Page);
17:
18: // the the Ivonna extension method to find the control
19: var wp = response.Page.FindRecursive<DemoWebParts.SpSimpleWebPart>("wp1");
20: Assert.IsNotNull(wp);
21:
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[0].Controls[0]).Cells[1].Controls[0] as Label;
25: Assert.IsNotNull(label);
26: Assert.AreEqual(“http://mockedsite.com”,label.Text);
27:
28: var list = ((TableRow)wp.Controls[0].Controls[1]).Cells[1].Controls[0] as DropDownList;
29: Assert.IsNotNull(list);
30: Assert.AreEqual(3, list.Items.Count);
31: }
```
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.