3.2. Unit Testing ASP.NET WebForms

An ASP.NET application is made up of two main parts. The aspx file contains the ASP.NET markup, which is a mixture of HTML, ASP.NET controls, and ASPX tags that contain code to be executed on the server before being returned to the user. The second part is the aspx.cs file that is the code-behind for a particular page. The code-behind files contain C# code to support the main ASP.NET page, allowing you to hook into the page lifecycle and execute code on the server when the page loads, or more commonly when a user requests some data that needs to be processed by the server.

However, because these code-behind files hook into the lifecycle of the page they have a tight dependency to the core ASP.net runtime. When it comes to testing, this tight dependency causes a huge amount of problems. If you attempt to access the object outside of the ASP.net runtime, such as when writing unit tests then you will receive a number of error messages in and around the core engine. When it comes to the aspx file, any of the code placed in the view is not accessible from another class — as such you wouldn't be able to write any unit tests for it.

In order to be able to unit test ASP.NET WebForms you need to think about how to develop the application in a different way. The most important thing to remember is to keep the view and the code-behind classes as thin as possible. They should contain the minimum amount of code to function and as soon as the code starts to ...

Get Testing ASP.NET Web Applications now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.