How to best do unit testing for a web application

Separate the logic and the UI portions - do not have all your business logic and complex code in the code behind page. Instead build them off the standard tier structure (data layer, business rules / logic layer, UI layer). This will ensure that your logic code you want to test does not reference the form, but instead uses classes that are easily unit tested.

For a very basic example, don't have code that does this:

string str = TextBox1.Text.ToString();
//do whatever your code does
TextBox2.Text = str;

Instead extract the logic into a separate class with a method:

TextBox2.Text = DoWork(TextBox1.Text.ToString());

public class Work
{
    public string DoWork(string str)
    {
      //do work
      return str2;
    }
}

This way you can write unit tests to verify that DoWork is returning the correct values:

string return = DoWork("TestThisString");

Now all of your logic is unit testable, with only code that HAS to reference the page directly still in your UI layer.


A very simple technique is the smoke test, where you automate a click-through of all of your application. If the script runs and there are no errors anywhere in the logs, you have at least one defined level of quality.

This technique actually catches a fair amount of regression breaks and is much more effective than it sounds like. We use selenium for this.

Tags:

Unit Testing