I am wondering how to test .aspx.cs and .ascx.cs code behind. Can I use unit testing and if so how? Are there alternatives that will help test the functions in the code behind files? I don't know how to mock the page or control.I would like to try to apply tdd methodology but I don't know how to unit test the code behind. Do you setup tests for the code behind or move the code to alternate files that are easier to test. Is moving the code out of the code behind a better practice? Also, how would you go about unit testing the code behind files?
Testing ASP.NET .aspx and .ascx code behind files
c#;unit testing;asp.net;tdd
.aspx files, compared to corresponding .aspx.cs code-behind files) are expected to contain minimum programming code, i.e. large chunks of HTML with here and there the calls to variables, eventually with straightforward loops and conditions.This means that you will rarely find unit tests for .aspx files, since there are no complicated algorithms or business rules there.Since .aspx files can still introduce bugs, system testing seems a good choice. The way would be the same as the one you use to test whether your HTML code corresponds to the requirements.Note: ASP.NET encourages to put too much programming code directly in .aspx files. In Microsoft's demos, you can even find SQL queries there. This is a terrible way to develop websites, and is misleading of what templates are.For example, in Django templates in Python, things are much clearer, and you don't put your database logic in HTML templates. ASP.NET makes separation of concerns not obvious.If you find yourself putting business logic or database logic in your HTML templates, or if you notice that many bugs are in your templates, consider introducing layers in your application, and keep only minimum code in templates.