1

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?

  • @gnat: I don't read this question as “what are best practice…”, but rather as “I try to apply TDD to templates, but I encounter technical constraints which make it impossible to do.” – Arseni Mourzenko Apr 5 '14 at 14:48
  • 1
    I re-worded it and took out "best practice" – DFord Apr 5 '14 at 14:50
3

.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.

0

It is actually pretty easy. All you need to do is to Extract the logic from Code behind/beside into Presenter class. All ASP.NET specific code should stay in code behind abstracted by View interface, that will be manipulated from Presenter. There is many examples on Model-View-Presenter pattern. Eg. http://blog.vuscode.com/malovicn/archive/2007/10/25/model-view-presenter-mvp-design-pattern-close-look-part-1-supervising-controller.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.