Unit Testing the Forgotten View In SharePoint Web PartsPosted 2011-03-24
A while back ago I had the opportunity to take part in the development of a SharePoint Web Part that should display a plain list of open orders in a SPGridView. My previous experience of SharePoint hadn't exactly been a fairytale and nicknames like SharePain and PainPoint were frequently used in our team. These nicknames are still used from time to time but experience has shown me that by using test-driven development when developing a SharePoint Web Part the implementation can be made rather friction free. But to be honest the deployment process is not my friend and weird things keep surprising me.
After all it was a great experience and we all learned a lot. One thing that I did observe when reading about unit testing SharePoint Web Parts was the lack of testing the View. The recommended approach when unit testing SharePoint Web Parts is to use the Model View Presenter (MVP) pattern, and there are many examples and guides that explain how to do it. But when reading all those examples and guidelines I noticed that they only tested the Presenter in MVP, and not the View. Some would argue that it isn’t necessary to test the View, but in our project we found it equally important to test the View as to test the Presenter, especially concerning the importance of when controls are added in the web part life cycle.
To unit test the View we created a testable web part that inherited from our web part, exposing methods to invoke the different events we were interested in. Below is a limited version of our testable web part, with reduced code and some renaming for easier demonstration.
As we were using the SPGridView we wanted to make sure that the control was added when creating child controls. When invoking the CreateChildControls method we could assert that the grid view was added.
We also created a testable grid view to get hold of the data that was bound to the web part.
As you can see there was no magic involved when unit testing the View. Our approach gave us a better understanding of how to work with SharePoint Web Part development and for all of you sharing my previous SharePoint experience I hope this can help you give it another shot.
Shameless plug: Are you a ninja? We are hiring in all our offices.