If you have been unit testing your asp.net web applications that use session and application variables then you almost certainly have encountered this problem and asked yourself \"How to unit test HttpContext.Current variables?\". The general answer you would find online is use a mocking framework (Moq, Rhino Mocks, etc.). While this is the best answer, it assumes that you have written your application using interfaces to pass objects from one place to another.

One of the first asp.net applications I was developing didn't use interfaces (I barely knew what they were), and had HttpContext.Current riddled throughout. After days of trying to find the correct way to unit test (without rewriting the whole application again) I came up with workaround. It is simple and does the job.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var username;
 
if(HttpContext.Current == null)
   //You can either hard code a session value 
   //username = "John Doe";
   //or get it from the web.config. 
   username = ConfigurationManager.AppSettings["UserName"];
else
   username = HttpContext.Current.Session["UserName"];
   

For inline declaration:

1
2
3
var username = HttpContext.Current == null ? 
                   ConfigurationManager.AppSettings["UserName"] :
                   HttpContext.Current.Session["UserName"];

Why does this work? When you are unit testing the application is not running on a web server, so there is no session state or application state meaning the HttpContext will be null.