title: mocking session variable in unit test using Moles
body: <p>Method I am unit testing checks for a session variable like</p>
  
  <pre><code>if(Session["somevar"] != null)
  {
     // rest of the code
  }
  </code></pre>
  
  <p>In my test, not able to get rid of this since <code>Session</code> is null, it's throwing null referrence exception.</p>
  
  <p>To bypass this, I have tried mocking it like below but no luck</p>
  
  <pre><code>System.Web.Moles.MHttpContext.AllInstances.SessionGet = (HttpContext cntx) =&gt;
  { return (HttpSessionState)cntx.Session["somevar"]; }
  </code></pre>
  
  <p>I even tried method mention <a href="http://haacked.com/archive/2005/06/11/simulating_httpcontext.aspx" rel="nofollow">here</a> to simulate HttpContext and then doing below</p>
  
  <pre><code>HttpContext.Current = new HttpContext(workerRequest);
  HttpContext.Current.Session["somevar"] = value;
  </code></pre>
  
  <p>But again no luck. This time, though the <code>HttpContext.Current</code> is not null but <code>HttpContext.Current.Session</code> and hence throws null ref exception.</p>
  
  <p>Any idea how can I mock this/by pass this in my test [Without using any external DLL or main code change. Sorry, but can't afford to do so].</p>
  
  <p>Thanks and appreaciate lot your help. </p>