HttpContext.Current.Session – Unit Testing

Here is a quick clever trick for failing over the connection string, in the case that it doesn’t already exist on the HttpContext.Current.Session object.

As you may know, Unit Testing frameworks don’t always mock out the HttpContext class properly, if at all.  This is unfortunate if you rely on objects stored there and you still want to unit test them.

string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;

try
{
    if (HttpContext.Current != null)
        if (HttpContext.Current.Session["ConnectionString"] != null)
            connectionString = HttpContext.Current.Session["ConnectionString"].ToString();

    using (var cn = new SqlConnection(connectionString))
   {
....

There are a lot of approaches to this problem, this is but one of them.

Hope this helps!

// Dave

This entry was posted in Development and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *