Fo unit testing ASP.NET controls I need a stubbed Page.
I can create an ASP.NET Page object in my unit tests by subclassing System.Web.UI.Page.
However, I cannot find a way to set Page.Form. Adding a form with attribute (runat,server)
does not work. Overloading the form in my Subclass does not give the required functionality.
Context:
I try to unit test some homemade ASP.NET controls. These control require Page and Page.Form not to be null.
Any suggestions?
Try defining an
IPageandIForminterface that implement the needed methods and properties and create classes that implements those interfaces and wraps aPageorFormclass. This way you can test the logic in those controls, without calling into the ASP.NET framework during unit testing.UPDATE:
Overriding the page property will be brittle and is not advisable. Instead, you should try to minimize the amount of untestable code, by extracting logic in methods that don’t depend on any ASP.NET specific (hard to test) parts. Take a look at the following example:
By extracting the logic out of methods that are hard to test, you can call those extracted methods directly in your tests. For instance:
It would be even better if you would be able to extract the code under test to it’s own class and call it from your WebControl. This is however, not always possible.
I hope this makes sense.