Working with Pages in Unit Tests

Despite what some may believe, you can work with ASP.NET in a unit-testing environment, though it is somewhat limited.  Certain objects that ASP.NET is able to utilize aren't available when unit-testing.  This is because a series of modules defined in the <httpModules> element in the master web.config setup these objects, which do not run during unit-testing.

How can this be countered?  Certain objects, like viewstate, and certain properties, like Page.IsPostback, work well in the unit-testing environment.  However, certain collections, like Session or Cache, do not.  To get around this, it is better to avoid it, or to use an alternative caching method like Enterprise Library's caching block.  In addition, you could create a method within a custom page class that reads/writes from the session/cache, which when in a unit testing environment, reads/writes to a local dictionary.  It could look like this:

public abstract class PageBase : Page
{
   protected void SetSessionValue(string key, object value)
   {
      if (HttpContext.Current != null)
          Session[key] = value;
      else
      {
          if (this.LocalSession.ContainsKey(key))
               this.LocalSession[key] = value;
          else
              this.LocalSession.Add(key, value);
      }
   }
}

LocalSession is a localized Dictionary<string, object> collection that works in the unit testing environment, and survives postbacks because there are no postbacks in unit testing, which is a challenge.  More on this later.

Comments

No Comments